简体   繁体   中英

Why does this for loop take so long?

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?

Your outer loop iterates 775146 times. That is the sqrt of 600851475143. Your inner loop iterates at least 5 times and increases. So the total number of iterations is at least 3875730. That takes a while.

Try inserting a count of the number of times your inner loop is entered. That count will be directly proportional to the run time of your code.

Your problem is probably caused by the fact that in Javascript, this code:

var primes = [2,3,5,7,11];
console.log(primes[12]);

produces the output undefined , even though primes[12] is way out of bounds of the array.

Javascript is not like other languages in this respect - going out of bounds of an array does not cause a crash but instead returns an undefined value and allows the program to merrily continue on. undefined is an actual value that can be stored in a variable, so it will continue to evaluate the if statements and exit the loop after the last iteration.

Comparisons against undefined are slow, at least in Chrome. See this Stackoverflow question for some performance information .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM