简体   繁体   English

通过Java中的Eratosthenes筛子求和:仅当参数为质数时失败

[英]Sum primes via Sieve of Eratosthenes in Javascript: Fails only if argument is prime

My implementation of the sieve itself seems to be working fine, and the summing function returns the correct result as long as the last value is not itself a prime number. 我对筛子的实现似乎运行良好,只要最后一个值本身不是素数,求和函数将返回正确的结果。 Oddly, I can see the primality is duly noted in the true/false array if I return it directly, but I can't seem to actually get at it for the purposes of summing. 奇怪的是,如果我直接返回原始性,则可以在true / false数组中看到原始性,但是出于求和的目的,我似乎并没有真正理解它。 As a result, running this Sieve on 10 returns 17 (correct), but running it on 37 returns 160 instead of 197. Running it on 5 returns 5 instead of 10, and so forth. 结果,在10上运行此筛将返回17(正确),但在37上运行将返回160而不是197。在5上运行将返回5而不是10,依此类推。

function sumPrimes(n) {
  var primArr = [];
  var primSum = 0;
  for (var i = 2; i < n; i++) {
    primArr[i] = true;
  }

  //sieve

  for (i = 2; i * i < n; i++) {
    if (primArr[i]){
      for (var j = 0; i * i + i * j < n; j++) {
        primArr[i * i + i * j] = false;
      }
    }
  }

  for (i = 2; i <= n; i++) {
    if (primArr[i]) {
      primSum += i;
    }
  }

  return primSum;
}

In all your for loops put the condition <= n , since you want to consider n itself as well. 在所有for循环中,将条件<= n放入,因为您也要考虑n本身。

Note that you save some calculations if you change the middle part to this: 请注意,如果将中间部分更改为此,则会保存一些计算:

for (var i = 2, sqrtN = Math.sqrt(n); i <= sqrtN; i++) {
    if (primArr[i]){
        for (var j = i * i; j <= n; j += i) {
            primArr[j] = false;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM