或循环内If语句中的布尔表达式

时间:2016-05-18 18:09:42

标签: javascript arrays if-statement boolean boolean-logic

当我通过Or Boolean语句检查数字以查看它是否为素数时,它不会完成检查,并返回整个数组。

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

2 个答案:

答案 0 :(得分:1)

你想要的逻辑是

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

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

当然,你需要考虑到这只适用于最高达48的素数。

答案 1 :(得分:1)

我建议你这样得"get prime numbers algorithm"

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;
}

并使用reduce

来总结
var sumPrimes = function(num) {
  var primes = getPrimes(num)
  var sum = primes.reduce(function(sum, prime) {
    return sum + prime
  }, 0)
}