A programming kata is an exercise which helps a programmer hone his skills through practice and repetition.

This article is part of the series "Scala Tutorial Through Katas". Articles are divided into easy, medium and hard. Beginners should start with easy ones and move towards more complicated once they feel more comfortable programming in Scala.

For the complete list of Scala katas and solutions please visit the index page

The article assumes that the reader is familiar with the basic usage of ScalaTest asserts and knows how to run them from his favorite Scala IDE (ours is IntelliJ IDEA with the Scala plugin).

Tests that prove that the solution is correct are displayed below. Recommended way to solve this kata is to write the implementation for the first test, confirm that it passes and move to the next. Once all of the tests pass, the kata can be considered solved.

One possible solution is provided below the tests. Try to solve the kata by yourself first.

# Prime Factors

Compute the prime factors of a given natural number.

[TESTS]

Test code can be found in the GitHub PrimeFactors.scala.

[ONE POSSIBLE SOLUTION]

The solution code can be found in PrimeFactors.scala solution.

What was your solution? Post it as a comment so that we can compare different ways to solve this kata.

Sergi GP (@SergiGP)mine 🙂

https://github.com/sergigp/scala-katas/blob/master/prime-factors/src/main/scala/PrimeFactorsCalculator.scala

Mr SvenssonYours run into problems when factoring products bigger than INT MAX.

Also, you continue the calculation from 2 every time, instead if continuing from where you found the first (smallest) factor.

object PrimeFactors {

def result(number: BigInt, start: BigInt = 2, list: List[BigInt] = Nil): List[BigInt] = {

Stream.iterate(start)(i => i + 1)

.takeWhile(n => n <= number)

.find(n => number % n == 0)

.map(n => result(number / n, n, list :+ n))

.getOrElse(list)

}

}

giriavatarthis code avoids the inner for loop

def primeFactors(number: Int): List[Int] = {

def loop(num: Int, factors: List[Int], divisor: Int): List[Int] = {

num match {

case 1 => factors

case _ =>

num % divisor match {

case 0 => loop(num/divisor, divisor :: factors, divisor)

case _ => loop(num, factors, divisor + 1)

}

}

}

loop(number, List.empty, 2).reverse

}