Skip to content

Instantly share code, notes, and snippets.

@odwrotnie
Last active August 29, 2015 13:57
Show Gist options
  • Save odwrotnie/9721655 to your computer and use it in GitHub Desktop.
Save odwrotnie/9721655 to your computer and use it in GitHub Desktop.
import annotation.tailrec
import collection.parallel.mutable.ParSeq
def factorize(n: Long): List[Long] = {
@tailrec
def factors(tuple: (Long, Long, List[Long], Int)): List[Long] = {
tuple match {
case (1, _, acc, _) => acc
case (n, k, acc, _) if (n % k == 0) => factors((n / k, k, acc ++ ParSeq(k), Math.sqrt(n / k).toInt))
case (n, k, acc, sqr) if (k < sqr) => factors(n, k + 1, acc, sqr)
case (n, k, acc, sqr) if (k >= sqr) => factors((1, k, acc ++ ParSeq(n), 0))
}
}
factors((n, 2, List[Long](), Math.sqrt(n).toInt))
}
(1 to 1000) foreach { i =>
val list = factorize(i)
list match {
case head :: Nil =>
println(f"It's prime $i%09d")
case _ =>
println(f"Factorized $i%09d -> ${list.mkString(", ")}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment