function sumPrimes(num) {
var start = 2;
var check = Math.sqrt(num);
var answer = [];
if ( num == start)
{
answer.push(num);
sum_primes(answer);
}
while(start <= check)
{
if(check%start === 0)
{
//do nothing and only increment the counter
start++;
}
else
{
answer.push(start);
}
}
sum_primes(answer);
}
function sump_primes(answer)
{
var sum = 0;
for(i=0;i<=answer.length;i++)
{
sum = sum + answer[i];
}
}
sumPrimes(10);
can someone please check as to where exactly the code is wrong.
TIA
Consider this, if ‘check % start !== 0’, does ‘start’ ever change?
please correct me if i’m wrong. my understanding is that this is a condition, which will either evaluate to true or false. for either of the outcomes ( true or false ), i’ve mentioned what is to be done.
i dont see where this is going wrong
Suppose check is 3.
- Since 2 <= 3, function enters loop.
- 3 % 2 === 1, hence 2 is pushed to answer.
- There is no change made to both start and check.
So, will start ever exceed check?
In other words, your loop never terminates if
start <= check && check % start !== 0
Also few more things not regarding the infinite loop:
- Your functions only returns undefined.
- Your second function attaches variable ‘i’ to global scope. Always, put ‘var’ keyword when declaring a variable. (If you can use ES6, use ‘let’ instead)
1 Like