I have the following exercise code where I’m trying to calculate the sum of all the primes from 1-10 which is crashing due to recursion.
I’m having trouble with my for and while loops as the code doesn’t seem to be cycling through my var i, and is getting stuck on the initial assignment of i = 3.
I’m not looking for the correct answer or the most efficient answer yet but I am looking for someone to help me understand what’s wrong.
Here’s the code:
var array = [2];
var total = 0;
var j = 0;
function isPrime(i, j) {
if ( i%array[j] === 0 ) {
console.log("i was " + i + " and j was " + j);
console.log(i + " is not a prime");
j = array.length;
}
else if ((j + 1) === array.length) {
console.log(i + " is a prime");
total += i;
console.log("total so far is " + total);
array.push(i);
console.log(array);
j = array.length;
console.log(j);
}
else {
j++;
isPrime(i,j);
}
}
for(var i = 3; i <=10; i++) {
while(j < array.length) {
console.log("i is " + i + " and j is " +j);
isPrime(i, j);
}
}
console.log(total);
console.log(array);
means that you have two distinct
jvariables: One outside the function, and one inside that shadows the other. From inside you never will be able to assign or read the outer variable. Therefore, the outerjstays0forever andwhile (j < array.length)will loop infinitely.