I think my code is right,but i get unexpected results on big numbers

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(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;


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.

Challenge: Sum All Primes

Link to the challenge:

How are your results different that you expect for large numbers?

Notice that the result for func(977) is off by exactly 977.

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.


Here again what is expected in the challenge!

Rewrite sumPrimes so it returns the sum of all prime numbers that are LESS OR EQUAL to num. That means (<= num). It was mentioned by @CactusWren2020

i already tried to put <= in my for loop.Still not working.Thanks

I restarted the browser and restart the code from the start and it worked.It seems it was just a bug.Thanks for the help!

You have to do it for:

for(let i=2; i<=num; i++)

and for:

for(let j=2 ;j<=num; j++)

I have checked that and it works!

1 Like

yeah i did it so many times,but it didnt.It was a bug,i fixed by restarting the browser and the challenge.Pfff sorry!

1 Like