Sum All Primes Fails Last Test

Tell us what’s happening:
Help why is my code failing for test sum Primes(977) should return 73156.
yet that’s the right answer i get on my console when testing the code
Help

Your code so far


function isPrime(num) {
  
  if(num<2) {
    return false;
  }
  for(let i=num-1;i>1;i--) {
    if(num%i===0) {
      return false;
    }
  }
  return true;
  
}

function sumPrimes(num) {
  let i = 1;
  let sum = 0;
  while(i<=num) {
    if(isPrime(i)) {
      sum+=i;
    }
    i++;
  }
  return sum;
}

sumPrimes(10);



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes

Just tried and it worked at the first shot ^^
I’m using mozilla ^^

Hi @MatricksDeCoder,

Your code is right, i don’t know why it is not working, but, here is another solution:

function sumPrimes(num) {
  // step 1	
  let arr = Array.from({length: num+1}, (v, k) => k).slice(2); 
  // step 2
  let onlyPrimes = arr.filter( (n) => { 
    let m = n-1;
    while (m > 1 && m >= Math.sqrt(n)) { 
      if ((n % m) === 0) 
        return false;
        m--;
    }
      return true;
  });
  // step 3
  return onlyPrimes.reduce((a,b) => a+b); 
}
sumPrimes(10);
sumPrimes(977);

Hope this help you to solve example, good luck my friend and have a nice day.

Regards,
Ali Mosaad

thanks read somewhere it could be to do with the browser i am using

thanks wow a beautiful solution i was thinking along those lines but kept missing a small bit

1 Like

@ali-admin @MatricksDeCoder Awesome work - both of you.

Could you do one little favor for the forum though? Wrapping those completed solutions in spoiler tags will hide them from those still working on that challenge. Anyone can still see your work by clicking on it though.
[spoiler]This text will be blurred[/spoiler]

Thank you

PS @MatricksDeCoder: Your code ran fine for me too. Not at all slow so probably not timing out.

Hi @alhazen1,

Thanks, I’ve edit my reply and put [spoiler], sorry if i confused you or any one in forum, good luck to every one here :slight_smile:

1 Like