Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a potential infinite loop in my JavaScript Code?

Tags:

javascript

I wish to find the sum of all prime numbers between range defined from 1 to N. The code gives an infinite loop when I call the sumPrimes function with a value of 3. I have debugged the code and found out that it does that only for the number 3. It does not do so for any other numbers above 2.

JavaScript:

function sumPrimes(num) { 
    var sum=0;
    for (i = 2; i <= num; i++) {
        if (checkPrime(i)) {
            sum += i;
        }
    }

    return sum;
}

function checkPrime(num) {
    for (i = 2; i <= Math.sqrt(num); i++) {
        if (num % i === 0) {
            return false;
        }
    }

    return true;
}
like image 401
Pranav Ghate Avatar asked Aug 09 '26 09:08

Pranav Ghate


2 Answers

Because you have to declare i with var : it will make it local to the function.

for (var i = 2; i <= num...

otherwise the two functions use the same global variable.

If you want to avoid this kind of bug, you should use strict mode. JavaScript Use Strict

You just have to put "use strict"; at the top of your .js file.

like image 131
A.Baudouin Avatar answered Aug 10 '26 22:08

A.Baudouin


You haven't declared a scope for i, which means that both loops will keep resetting the value of i in global scope, causing the loop to continue endlessly.

Add var i to the top of both functions and the problem will disappear.

like image 40
zzzzBov Avatar answered Aug 10 '26 22:08

zzzzBov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!