I tried this function in scala. Here is my result:
def getPrimeFactores(i: Int) = { def loop(i: Int, mod: Int, primes: List[Int]): List[Int] = { if (i < 2) primes // might be i == 1 as well and means we are done else { if (i % mod == 0) loop(i / mod, mod, mod :: primes) else loop(i, mod + 1, primes) } } loop(i, 2, Nil).reverse }
I tried to make it as functional as possible.
if (i % mod == 0) loop(i / mod, mod, mod :: primes)
checks if we have found a divisor. If we did this, add it to primes and divide it modulo.
If we did not find a new divisor, we simply increase the divisor.
loop(i, 2, Nil).reverse
initializes the function and arranges the result more often.
source share