recursion - Javascript for summing primes crashing -
i have next exercise code i'm trying calculate sum of primes 1-10 crashing due recursion. i'm having problem , while loops code doesn't seem cycling through var i, , getting stuck on initial assignment of i = 3. i'm not looking right reply or efficient reply yet looking help me understand what's wrong. here's code:
var array = [2]; var total = 0; var j = 0; function isprime(i, j) { if ( i%array[j] === 0 ) { console.log("i " + + " , j " + j); console.log(i + " not prime"); j = array.length; } else if ((j + 1) === array.length) { console.log(i + " prime"); total += i; console.log("total far " + total); array.push(i); console.log(array); j = array.length; console.log(j); } else { j++; isprime(i,j); } } for(var = 3; <=10; i++) { while(j < array.length) { console.log("i " + + " , j " +j); isprime(i, j); } } console.log(total); console.log(array);
var j = 0; function isprime(i, j) { …
means have 2 distinct j
variables: 1 outside function, , 1 within shadows other. within never able assign or read outer variable. therefore, outer j
stays 0
forever , while (j < array.length)
loop infinitely.
javascript recursion for-loop while-loop primes
No comments:
Post a Comment