1

When I check the number to see if it is prime via the Or Boolean statement, it does not complete the check, and it returns the entire array.

function sumPrimes(num) {
  var arr = [];

  var prime;
  for(var i = 1; i <=num; i++){
   if(i%2 !== 0 || i%3 !== 0 || i%5 !== 0){
     arr.push(i);
   }
  }
  return arr;
}

sumPrimes(10);
Pointy
  • 405,095
  • 59
  • 585
  • 614

2 Answers2

1

The logic you want is either

if (i%2 !== 0 && i%3 !== 0 && i%5 !== 0) // not divisible by 2 and not divisible by 3
                                         // and not divisible by 5

or

if (!(i%2 === 0 || i%3 === 0 || i%5 === 0)) // not divisible by 2 or 3 or 5

And of course you need to consider that this only works for primes up to 48.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

I'd suggest you just get a "get prime numbers algorithm" like this:

function getPrimes(max) {
  var sieve = [], i, j, primes = [];
  for (i = 2; i <= max; ++i) {
      if (!sieve[i]) {
          // i has not been marked -- it is prime
          primes.push(i);
          for (j = i << 1; j <= max; j += i) {
              sieve[j] = true;
          }
      }
  }
  return primes;
}

And sum that up using reduce

var sumPrimes = function(num) {
  var primes = getPrimes(num)
  var sum = primes.reduce(function(sum, prime) {
    return sum + prime
  }, 0)
}
Community
  • 1
  • 1
lipp
  • 5,586
  • 1
  • 21
  • 32