Sum All Primes, output too high

Sum All Primes, output too high
0

#1

Tell us what’s happening:
with higher numbers (977) i keep getting too high a number as output. i have no idea what i’m doing wrong

Your code so far

function sumPrimes(num) {
 var a = [2,3,5,7];
for (var i = 2; i < num;i++){ 
if (i % 2 !== 0){
if( i % 3 !== 0){
if(i % 5 !== 0){
if(i % 7 !== 0){ a.push(i);}}}}
}
   var total = a.reduce(function(sum, value) {
  return sum + value;
}, 0);
console.log(a);
  return total;
  
 
}

sumPrimes(977);

Your browser information:

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

Link to the challenge:


#2

You’re generating numbers that aren’t prime. 121 jumps out because it’s the square of 11.


#3

thank you!

now i truly have no idea what i’m doing.


#4

I am going to use pseudo-code to help you understand what logic you still need to figure out. This is not the only way or most efficient way to do it, but I wanted to use as much of your code as possible.

function sumPrimes(num) {
  create an empty arr called a
  for (var i = 2; i < num;i++){ 
    if i is a prime number {
      a.push(i);
    }
  }
  var total = a.reduce(function(sum, value) {
    return sum + value;
  }, 0);
  return total;
}

sumPrimes(977);

The part written in plain language is the part you need to figure out how to implement. You could create a function called isPrime and have it return true if the value passed into it is a prime number. If it returns true, then you push the value into the array called a.

What you need to understand is how a prime number is defined:

A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.


#5

yeah, i saw something like that in the wikipedia article on the Sieve of Eratosthenes.
still don’t get it yet.
what is the absolute mathematical proof that a number is prime or not, using variables?
i thought eliminating all the smallest possible primes was enough, but it appears i’m wrong.

you helped me a lot, thank you.
but i guess i have to take a week and figure this out like i did with all the other problems


#6

The Sieve of Eratosthenes is a good algorithm to solve this challenge. Take the time to understand what it is doing and you will be able to use what you learn in other more complicated problems.


#7

i think i understand what it is doing
its 1) making an array of numbers 2) sorting them into piles of prime, or multiples of prime 3) then spits out only primes.

wouldn’t that slow the process down a ton if i make a whole array of numbers, sort through those numbers and put them into two new arrays, then take the one array i need and multiply it?