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