Sum All Primes - Feedback on solution

Tell us what’s happening:
I managed to pass the test with the code below. I checked the official guide and it was totally way off from the solutions provided.

Coding/function wise would this be acceptable? I supposed this is inefficient and execution error may occur?



function sumPrimes(num) {

let sum = 0;
  for (let i = num; i > 1; i--) { // iterate starting from i = num to 2)
    let n = i-1;
    while (i % n !== 0 && n > 1) {
      n--;            // while loop to test if i is prime
    }                 // i is prime if while statement loops completely
    if (n == 1) {     // n == 1 if while executes all the way
      sum +=i;
    }
  }
  return sum;
}

sumPrimes(10);

Your browser information:

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

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

Hello Ed,

Yes it is. For checking a prime you may start checking the mod(%) from 2 to root of the number(sqrt), also note you may not check all numbers in the range one-by-one! actually prime numbers between them could do the trick.

But since you may not have a list of prime numbers, at least you can go for two-step on odd numbers, since when something is not mod to 2, so surely it won’t be mod to 4, 6 , 8,…
the same story about the 3, 6, 9 …

You should not think that level for now, becasue if you are thinking performance, you will find out you can do it parallel.

I’m not math expert, but I think if you start from 2, then 3 and go for odd numbers till sqrt is a good move.

(Thanks @luandy64 my great math comrade for math tips so far)

Happy coding.

1 Like