I'm solving Problem 3 in Project Euler:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143?
Most answers I found made use of array to store the prime factors and iterate over them to find the greatest one which doesn't seem good.
I'm recently learning js and this doesn't seem to me quite javascript-ish way of doing. Is there any way to refactor this?
var highestPrime = 2;
function divide (limit){
for (var i=3; i<Math.floor(limit/2)+1; i++) {
if (limit%i == 0){
compareIfEven(i); // callback to check if it's even divisor
}
}
return highestPrime;
}
function compareIfEven(i){
if (i % 2 !== 0){
compareIfPrime(i); // if not even, callback to compare if it's prime
}
}
function compareIfPrime(i) {
for (var j=3; j<i; j++) {
if (i%j !== 0){ // if a prime divisor, assign it the value highestPrime
highestPrime = i;
}
}
}
console.log(divide(600851475143));
It works for smaller values but goes over memory limit for asked value. Is there any way to make it efficient?
fountIt
forfoundIt
, it gives the wrong result for the test case13195
, outputting2639
rather than29
. \$\endgroup\$