简体   繁体   English

使用Eratosthenes筛子的素数总和找不到错误

[英]Sum of Primes using Sieve of Eratosthenes can't find bug

I'm working in JavaScript and this is a bit confusing because the code is returning the correct sum of primes. 我正在使用JavaScript,这有点令人困惑,因为代码返回正确的素数之和。 It is working with larger numbers. 它正在处理大量数字。 There is a bug where for 977 it returns the sum of primes for 976, which is 72179, instead of the sum for 977 which is 73156. Everything I've test so far has come back correctly. 有一个错误,其中977返回976的质数之和为72179,而不是977返回的质数之和为73156。到目前为止,我测试过的所有内容都已正确返回。

function sumPrimes(num) {

    var sum = 0;
    var count = 0;
    var array = [];
    var upperLimit = Math.sqrt(num);
    var output = [];

    for (var i = 0; i < num; i++) {
        array.push(true);
    }

    for (var j = 2; j <= upperLimit; j++) {
        if (array[j]) {
            for (var h = j * j; h < num; h += j) {
                array[h] = false;
            }
        }
    }

    for (var k = 2; k < num; k++) {
        if (array[k]) {
            output.push(k);
        }
    }

    for (var a = 0; a < output.length; a++) {
        sum += output[a];
        count++;
    }

    return sum;
}

sumPrimes(977);

The problem stems from the fact that your "seive" Array is indexed from 0, but your algorithm assumes that array[n] represents the number n . 问题源于“ seive” Array从0开始索引的事实,但是您的算法假定array[n]代表数字n

Since you want array[n]===true to mean that n is prime, you need an Array of length 978 if you want the last item to be indexed as array[977] and mean the number 977 . 由于您希望array[n]===true表示n为质数,因此如果要将最后一项索引为array[977]表示数字977 ,则需要一个长度为978Array

The issue seems to be fixed when I change all instances of < num to < num+1 . 当我将所有< num实例更改为< num+1时,该问题似乎已解决。

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

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