3

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;
}
11
  • 1
    How can i be less than 1.73, if it begins at 2? Commented Jul 6, 2016 at 15:19
  • 1
    There is no infinite loop on 3. However, it won't do anything for 3, as the square root of 3 is less than 2, so it will simply return true. Which is actually correct, as 3 is prime. Commented Jul 6, 2016 at 15:19
  • @GerardoFurtado it works for the number 2 though, I am confused as well Commented Jul 6, 2016 at 15:20
  • 3
    @ManoDestra, fixing the code in the question hides the actual problem. Commented Jul 6, 2016 at 15:23
  • 1
    holy hell thanks guys, it was the absence of 'var' Commented Jul 6, 2016 at 15:32

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

And would you then please explain why that omission (which occurs in two places in the posted code) would produce "an obviously very-subtle bug?" It does not matter that the variable is used within the body of a function? Interesting ... (And yet-another reason why I long ago stopped writing source-code directly in JavaScript ...!)
Doesnt matter if var is used or not
It does matter. You need to add var prior to i in both functions above.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.