Scala Prime Factors Kata

So recently I started committing myself to understanding scala better and a perfect way of doing this is to start practicing different code katas in the language. So early this morning I started the day by doing the Prime Factors Kata in scala using specs to drive development and sbt to build run tests. The thing I really like about sbt is you can run ~test and just like ZenTest file changes triggers all the specs in the project to be re-ran.

Overall my solution was pretty simplistic and comes from a java developer’s understanding of scala. I spent 30 minutes on it and shared the result on github under scala-prime-factors. Feel free to criticize to your heart’s desire and let me know of better ways of solving this… I keep feeling like there must be a simple scala one liner that I just don’t know about. ;)

For those who are lazy, here is the spec:

import org.specs._

class primeFactorsSpec extends Specification {
  "should generate empty list for 1" in {
    primeFactors.generate(1) must be equalTo(List[Int]())
  }
  "should generate a list with 2 in it for 2" in {
    primeFactors.generate(2) must be equalTo(List[Int](2))
  }
  "should generate list with 3 in it for 3" in {
        primeFactors.generate(3) must be equalTo(List[Int](3))
  }
  "should generate a list with 2 and 2 in it for 4" in {
    primeFactors.generate(4) must be equalTo(List[Int](2,2))
  }
  "should generate a list with 2 and 3 in it for 6" in {
    primeFactors.generate(6) must be equalTo(List[Int](2,3))
  }

  "should generate list with three 2s for 8" in {
    primeFactors.generate(8) must be equalTo(List[Int](2,2,2))
  }
  "should generate list with two 3s for 9" in {
    primeFactors.generate(9) must be equalTo(List[Int](3,3))
  }
}

And here is the terrible looking solution:

object primeFactors{
  def generate(n:Int) = {
    var x = n
    var factors = List[Int]()
      for(i <- 2 to n)
        while(x % i == 0 && x/i > 1){
          factors += i; x/=i
        }
    if(x > 1)
     factors += x
  factors
  }
}
You can leave a response, or trackback from your own site.

Facebook comments:

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!