 # [help - SPOILERS] sum All Primes - code works but won't pass tests[SOLVED]

Hello everyone,

I am having a tough time with the sum All primes algorithm. The code I have returns the correct values on JS bin without any console errors:
js bin - sum all primes

When I run the code on code camp, it throws this error: "potential infinite loop at line 8… " which is where I set “notPrime = false” below. I have tried adding //noprotect as line 1 of code. The code runs and returns the sum, but the test do not pass.

``````var arr = []; //store prime numbers here

//primeBelow pushes prime numbers <= val into arr array
function primeBelow(val){
//test all numbers between 2 and val for prime
var notPrime;
for (var numTest = 2; numTest <= val; numTest++){
notPrime = false;
//divide i by all numbers below i.
//If any division has zero remainder, its not prime.
for (var i = 2; i<=numTest; i++){
if (numTest%i === 0 && numTest != i){
notPrime = true;
}
}
//if the prime test is passed, push the value to arr
if (notPrime === false) {
arr.push(numTest);
}
}
return arr;
}

//sumPrimes call the primeBelow function and sums all prime values below num
function sumPrimes(num){
var sum = 0;
primeBelow(num);
arr.map(function(val){
sum += val;
});
console.log(arr, sum);
return sum;
}

sumPrimes(977);
``````

I don’t see where the infinite loop warning is coming from, or what I am missing. Browsers tried: Chromium and Firefox

Any insights would be greatly appreciated. Thanks for reading!

I’m not sure of the exact reason why this is the case, but I think it is because you declare the `arr` outside of the two functions that reference it.

I modified your code slightly and it worked:

Spoiler
``````// I deleted the line below:
// var arr = []; //store prime numbers here

function primeBelow(val){
// I added the arr here:
var arr = [];
var notPrime;
for (var numTest = 2; numTest <= val; numTest++){
notPrime = false;
for (var i = 2; i<=numTest; i++){
if (numTest%i === 0 && numTest != i){
notPrime = true;
}
}
if (notPrime === false) {
arr.push(numTest);
}
}
return arr;
}

function sumPrimes(num){
var sum = 0;
// Notice here I pass the arr variable between the functions
// by assigning the return value of the other function to the
// arr variable in this function
var arr = primeBelow(num);
arr.map(function(val){
sum += val;
});
return sum;
}

sumPrimes(10);
``````
1 Like

Thank you jacksonBates! I was banging my head against this wall for too long. I had tunnel vision on that if statement. I never looked at the rest of the code, let alone think that the simple variable declaration could have been the cause.

thanks, and Cheers Sir! 