Reputation: 57
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;
}
Upvotes: 3
Views: 235
Reputation: 2925
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.
Upvotes: 4
Reputation: 179046
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.
Upvotes: 1