Skip to content

Instantly share code, notes, and snippets.

@landon9720
Created June 25, 2012 17:43
Show Gist options
  • Select an option

  • Save landon9720/2990101 to your computer and use it in GitHub Desktop.

Select an option

Save landon9720/2990101 to your computer and use it in GitHub Desktop.
prime factorization in scala
// borrowed from http://louisbotterill.blogspot.com/2009/03/prime-factorization-comparison-between.html
def factors(n:Int):List[Int] = {
def divides(d:Int, n:Int) = (n % d) == 0
def ld(n:Int):Int = ldf(2, n)
def ldf(k:Int, n:Int):Int = {
if (divides(k, n)) k
else if ((k*k) > n) n
else ldf((k+1), n)
}
n match {
case 1 => Nil
case _ => val p = ld(n); p :: factors(n / p)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment