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);
0

2 Answers 2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.