Skip to content

Instantly share code, notes, and snippets.

@YanivHaramati
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YanivHaramati/5590a2cbc7703cb23d4d to your computer and use it in GitHub Desktop.
Save YanivHaramati/5590a2cbc7703cb23d4d to your computer and use it in GitHub Desktop.
Largest prime factor for n
// find largest prime factor of n
function primeFactorization(n) {
// begin by fetching the first 100 primes. if this proves insufficient we'll get more by multiplying the count by 10 each time.
var primeCount = 100;
var primes = getPrimes(primeCount);
var factors = [];
var temp = n;
for (var i = 0; primes.indexOf(temp) < 0; i++) {
if (i > primes.length - 1) {
primeCount *= 10;
primes = getPrimes(primeCount);
}
if (temp % primes[i] == 0) {
temp = temp / primes[i];
factors.push(primes[i]);
}
}
// if the last division is a prime then add it as a factor.
if (primes.indexOf(temp) >= 0) factors.push(temp);
return Math.max.apply(null, factors);
}
function getPrimes(n) {
var primes = [2, 3];
for (var i = 5; primes.length < n; i += 2) {
if (primes.every(function (p) { return i % p; })) {
primes.push(i);
}
}
return primes;
}
function test(actual, expected, err) {
if (actual === expected) console.log("SUCCESS");
else err(actual, expected);
}
function errMsg(actual, expected) {
console.error("ERROR. Found: " + actual + " but expected: " + expected);
}
test(primeFactorization(600851475143), 6857, errMsg);
@YanivHaramati
Copy link
Author

for a way more efficient implementation of getPrimes: https://gist.github.com/YanivHaramati/177030fbefa0d0d2879f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment