Sum All Primes pls give me a hint

Sum All Primes pls give me a hint
0

#1

Tell us what’s happening:
Well, this code seems like true, but i know that something’s wrong, it passes 2 challenges but not really close to passing 3rd. Pls give me a hint cuz i cant’t really find stuff to change atm.

Your code so far


function sumPrimes(num) {
  let numb=1;
  let deleter=1;
  let count=0;
  let sum=0;
  for (numb;numb<=num;numb++){
    if (count===2){
      sum+=numb-1;
    }
    count=0;
    for(divider=1;divider<=num;divider++){
      if (Number.isInteger(numb/divider)===true){
        count++;
      }
    }
  }
return sum;
}
sumPrimes(977);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0.

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


#2

You might be hitting an internal timer in the testing suite. That would cause your test to fail. You need to find a more efficient method of finding primes.

If you need an idea, read up on the sieve of Eratosthenes. Might be enlightening if you can’t think of a way to improve your current algorithm.


#3

The approach you’ve taken is WILDLY inefficient – also, the first time through the inner loop, you’re dividing numb by one – so it should always return true. Is that your intent?

Using two loops that iterate over the same set of numbers, nested – in the case of 977, you’re iterating 977^977 times – in effect, you’ve created yourself a google loop. Fun times. To see the actual value, try opening a console and type in Math.pow(977^977) – you won’t like the result. You’ve created an infinite loop.

Definitely look into the Sieve of Eratosthenes, it is an elegant, easily implemented solution.


#4

Yeah, Thank you, well i know that this algorithm is extremly uneffective, and i’d better look for more effective one. just wondered if there are any mistakes technicaly in code.


#5

Not to be a smart alec, but the fact that it doesn’t scale to four places (thousands or above) is a technical problem. Your question was why the third test doesn’t pass. It times out, if I had to guess.

Technically, your solution works fine. Assuming unlimited computing power and no timeout issues. It is a brute-force approach, checking each and every number to see if its divisible by every number below it, over and over. IT IS TECHNICALLY ACCURATE. It will blow the crap out of any system at scale.