Created
October 15, 2009 00:09
-
-
Save Synesso/210518 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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