freeCodeCamp Challenge Guide: Sum All Primes Update

I checked out the guide: freeCodeCamp Challenge Guide: Sum All Primes and the solutions it included and it seems so complicated and hard to understand.

If you think about the prime numbers. You realize that 2 is the only even prime number. All other prime numbers are odd. So you don’t need to generate something like [2, 3, 4, 5, 6, 7, …]. You only need to generate an array full of odd numbers, like this [3, 5, 7, 9, …].

Then you filter the array full of the odd numbers to see if they are able to be divided by every prime odd number with no remainder and push the odd number with the remainder to the prime array and then unshift “2” to the beginner of the array and sum all the prime array up.

Here’s my solution:

function sumPrimes(num) {
  let primeArr = [];
  for(let i = 3; i <= num; i+=2){
    if(primeArr.every((prime) => i%prime !=0)) {
      primeArr.push(i);
    }
  }
  primeArr.unshift(2);
  return primeArr.reduce((a, b) => a + b);
}

console.log(sumPrimes(10));
3 Likes