I have been working on the Project Euler questions, and in solving question 3 I came across something odd.
Question 3 asks you to "Find the largest prime factor of the number 600851475143"
I solved it as so:
var search = 600851475143;
var highest = 0;
var primes = [2,3,5,7,11];
function isPrime(num) {
for (var i = 0; i < primes.length; i++) {
if (num === primes[i]) {
return true;
}
else if (num % primes[i] === 0) {
return false;
}
}
primes.push(num);
return true;
}
for (var n = 2; n <= Math.floor(Math.sqrt(search)); n++) {
if (isPrime(n) && search % n === 0) {
highest = n;
}
}
console.log(highest);
This took 7534.188ms this was actually my second version of the program.
In the first version the only difference was that in the for loop in the isPrime function stated
i <= primes.length
When this change was in place the program took 72084.540ms
That is a rise from around 8 seconds to around 72 second, that is 9 times slower.
I do not believe that the extra iteration would account for such an increase in time. My initial thought was that as it was looking for an index that does not exist, but surely this would crash the program and not just cause it to run slower.
Does anyone have any insight into this?