Sum of all prime numbers

Tell us what’s happening:
So, I believe I’ve found a very efficient way to solve this exercise by iterating only over the prime numbers array and the numbers smaller than num

I’ve used a very simple mathematical insight for this: Every integer greater than 1 is either a prime number, or the product of two or more prime numbers

Take the first 5 primes: 2, 3, 5, 7, 11;
5, as you know, doesn’t have 2 or 3 (the only primes smaller than 5) as factors, thus 5 is prime

15 can be written as 3 * 5, which means it’s not prime.
22 can be written as 2 * 11, which means it’s not prime

So we don’t have to check if a number is divible by any other numbers smaller than its half to know if it’s prime, we only have to test it against other primes

I don’t think I’m the first to do this, I just wanted to share it because it’s not one of the solutions listed to the challenge

Your code so far


function sumPrimes(num, arr = []) {
if (num <= 1) return
for (let next = 2; next <= num; next++)
  if (!arr.some(val => next % val === 0)) arr.push(next) 
return arr.reduce((a, b) => a + b)
}

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/86.0.4240.111 Safari/537.36.

Challenge: Sum All Primes

Link to the challenge:

Hi and welcome to the forum!

This is a good approach. If I am not mistaken though, this is the approach taken by Solution 4.

1 Like

actually, you can check numbers just until its square root, there is never a number that does not have divisors equal or less than its square root, unless it’s prime

2 Likes

Thank You!! :smiley:
Also, Solution 4 is in fact pretty similar, it generates an array with all integers n with 2 < n < num, then it filters elements that can be divided by other elements out of the array

I never noticed that. Thanks :smiley: