Sum All Primes Error

Sum All Primes Error
0

#1

Tell us what’s happening:
When I’m trying to run the program on code editor it returns the expected result but why it’s not working here,
The last one is not getting correct


Your code so far


function sumPrimes(num) {
  var sum = 0;
  for (var counter = 2; counter <= num; counter++) {

    var notPrime = false;
    for (var i = 2; i <= counter; i++) {
      if (counter % i === 0 && i !== counter) {
        notPrime = true;
      }
    }
    if (notPrime === false) {
    sum += counter;
    }
  }
  return sum;
}

console.log(sumPrimes(977));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

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


#2

When I run your code the Chrome and Edge debuggers I get the results expected. What browser are you using, Safari? I don’t have access to that one.

When I look at your screenshot, you’re getting 73156 for sumPrimes(977), which is correct. What are you seeing that is not correct?


#3

It may be that your function is timing out. you need to find a more efficient way to get the result.


#4

https://forum.freecodecamp.org/t/free-code-camp-infinite-loop-protection/19550


#5

You’re doing too many calculations that aren’t needed, so it is timing out. The reason it works locally for you but doesn’t on the tests is that the tests will time out after a few milliseconds, whereas your system can basically take as long as you want.

There is the infinite loop protection, and removing that may fix it instantly, but that still won’t help for things that are genuinely long-running processes. And the algorithm you have used is not a good one in this case (it is just brute force, going through every possible number over and over again), so it would be good practise to fix it properly.

So you need to find a way of optimizing your algorithm. A few ways to start off with:

  • You’re checking even numbers: no even number except 2 is a prime, so all those extra checks are pointless.
  • This also applies for multiples of 3, 5, etc etc.
  • You can memoize the function. Initialise an object at the top of the function: that will be used to store results. For every result you calculate, check in the store: if it’s in the store already, use the value in the store. If it isn’t, check it’s a prime and also put the result in the store.

#6

thanks for updating me