Skip to content

Instantly share code, notes, and snippets.

@Synesso
Created October 15, 2009 00:09
Show Gist options
  • Save Synesso/210518 to your computer and use it in GitHub Desktop.
Save Synesso/210518 to your computer and use it in GitHub Desktop.
def factorise(l: Long): Map[Long, Int] = {
def innerFactorise(l: Long, primes: List[Long], factors: List[Long]): List[Long] = {
def expandPrimes: List[Long] = {
def innerExpand(candidate: Long): List[Long] = {
val maxFactor = Math.sqrt(candidate).toLong + 1l
val factors = primes.takeWhile(_ < maxFactor).dropWhile(candidate % _ != 0)
if (factors.isEmpty) primes ::: candidate :: Nil else innerExpand(candidate + 1)
}
innerExpand(primes.last + 1)
}
primes.last match {
case x if (x == l) => (x :: factors).reverse
case x if (l % x == 0) => innerFactorise(l / x, primes, x :: factors)
case _ => innerFactorise(l, expandPrimes, factors)
}
}
innerFactorise(l, List(2), Nil).foldLeft(Map.empty[Long, Int]) {(acc, next) =>
acc(next) = acc.getOrElse(next, 0) + 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment