Created
January 8, 2017 13:43
-
-
Save Muzietto/610a010b78dcbccedac735da8920a9dc to your computer and use it in GitHub Desktop.
Eratosthenes to the rescue in finding prime factors of a given number
This file contains hidden or 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
function primeFactorsOf(n) { | |
var lpfs = leastPrimeFactorsOf(n); | |
return helper(lpfs, n, []); | |
function helper(lpfs, n, arra) { | |
if (lpfs[n] == 0) return arra.concat([n]); | |
return helper(lpfs, n/lpfs[n], arra.concat([lpfs[n]])); | |
} | |
} | |
function leastPrimeFactorsOf(n) { | |
var sieve = new Array(n + 1).fill(0); | |
for (var i = 2; i <= Math.ceil(Math.sqrt(n)); i++) { | |
for (var j = 2; j <= n; j++) { | |
if (j > i && j % i === 0 && sieve[j] === 0) sieve[j] = i; | |
} | |
} | |
return sieve; | |
} |
Author
Muzietto
commented
Jan 8, 2017
primeFactorsOf(42122344)
...still thinking about it
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment