Skip to content

Instantly share code, notes, and snippets.

@mattdiamond
Last active May 6, 2019 16:53
Show Gist options
  • Save mattdiamond/f7302472e0ce6eb0a50d65efaabaa7f2 to your computer and use it in GitHub Desktop.
Save mattdiamond/f7302472e0ce6eb0a50d65efaabaa7f2 to your computer and use it in GitHub Desktop.
function primeFactors (n) {
if (n <= 1) return [];
if (n % 2 === 0) {
return [2, ...primeFactors(n / 2)];
}
const root = Math.sqrt(n);
let divisor = 3;
while (n % divisor) {
divisor += 2;
if (divisor > root) {
return [n];
}
}
return [divisor, ...primeFactors(n / divisor)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment