Skip to content

Instantly share code, notes, and snippets.

@Muzietto
Created January 8, 2017 13:43
Show Gist options
  • Save Muzietto/610a010b78dcbccedac735da8920a9dc to your computer and use it in GitHub Desktop.
Save Muzietto/610a010b78dcbccedac735da8920a9dc to your computer and use it in GitHub Desktop.
Eratosthenes to the rescue in finding prime factors of a given number
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;
}
@Muzietto
Copy link
Author

Muzietto commented Jan 8, 2017

primeFactorsOf(4212234)
> [2, 3, 3, 13, 47, 383]

@Muzietto
Copy link
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