Sum All Primes - Large Number Weirdness

Sum All Primes - Large Number Weirdness
0

#1

Tell us what’s happening:
Hey all.

I am having a hard time figuring out why this solution won’t work. It passes the first two tests but not the last. It also gives me the correct result for numbers that I manually put into the function and check for manually by looking up prime charts and doing the math (I can only do so many though). Somewhere along the line this code falls off the horse.

I’m using a counter to test for prime since each prime can only have two divisions where the remainder is 0 (right?). I would be grateful for any insight.

Note! When I console.log 977, the result is not always the same number. If I delete part of the code and then re-type the exact same part that I deleted, it will generate slightly different numbers. I tested this many times. Even just deleting a semi-colon and then putting it back in will sometimes change the result to a seemingly random number around 69,000… strange.
Your code so far


function sumPrimes(num) {
  var primeCandidate = 2;  // start with the first prime.
  var primeSum = 0;
  
  while (primeCandidate <= num) {
    var divisor = 1;
    var divisionCount = 0;

    while (divisor <= primeCandidate) {
      if (primeCandidate % divisor === 0) {
        divisionCount++;
      }
      divisor++;
    }

    if (divisionCount === 2) primeSum += primeCandidate;
    primeCandidate++;
  }

  return primeSum;
}

console.log(sumPrimes(977));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes


#2

Add //noprotect at the top. It’s just too slow.



#3

Thanks for the reply.

I can’t get //noprotect to work on line one, nor can I get it to work if I place it above every line of code.

Unlike the other users who have encountered this problem, I’m not getting the correct result with the test failing, I’m simply not getting the correct number. This makes me think it’s my code and not the time-out function.

Should I just give up this approach and find another solution? I’d really like to know why my code is tanking before moving on.

EDIT: //noprotect works now. Odd that it didn’t the first few tries. Thanks for the solution!