Tell us what’s happening:
So i solved the challenge where i had to find the sum of all previous numbers of the given number.I think my code is wright but i get strange numbers when i pass the 977 number as an example.Can anyone help?
Your code so far
function sumPrimes(num) {
let primesArray=[];
let timesCounter=0;
for(let j=2;j<=num;j++){ //check each previous number if is a prime
timesCounter=0; //how many times he will get divided and give 0 are a result
for(let i=2;i<=num;i++){
if(j%i==0){
timesCounter++;
}
}
if(timesCounter==1) primesArray.push(j) //if he got divided only one time he is a prime
}
let sumOfPrimes = primesArray.reduce((sum,item)=>sum+item,0); //get the sum of all the primes
return sumOfPrimes;
}
sumPrimes(120);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36.
There is an example on wikipedia for prime numbers with number 120.I tried 120 on my funciton,consoled.log the array and it worked fine.But when i go on 977,it is not.I am confused a bit.
Oh i just saw on the console that there is a potential infinite loop,test’s may fail.But i dont get it,how there is not an infinite loop when i give the numbers 10 and 121 for an argument but there is when i give 977?
I also run this code on scrimba.com and it works fine with 977 as an argument.