Last active
August 29, 2015 14:18
-
-
Save YanivHaramati/5590a2cbc7703cb23d4d to your computer and use it in GitHub Desktop.
Largest prime factor for n
This file contains 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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for a way more efficient implementation of getPrimes: https://gist.github.com/YanivHaramati/177030fbefa0d0d2879f