简体   繁体   English

为什么Eratosthenes Sieve的实施不正确?

[英]Why is this implementation of Sieve of Eratosthenes incorrect?

The goal is to find the sum of all primes up till num. 目标是找到所有素数的总和直到num。 I've seen the same implementation on another post, but it also doesn't work: Sieve of Eratosthenes algorithm in JavaScript running endless for large number 我在另一篇文章中看到了相同的实现,但它也不起作用: 在JavaScript中运行Eratosthenes算法的Sieve对大量运行无穷无尽

However, the solution there is also incorrect when I try it with 977, it returns 72179, but it should be 73156. 但是,当我用977尝试它时,解决方案也是不正确的,它返回72179,但它应该是73156。

const sumPrimes = num => {
    var numList = [];
    var output = [];
    for (var i = 0; i < num; i++) {
        numList.push(true);
    }

    for (var i = 2; i <= Math.sqrt(num); i++) {
        if (numList[i]) {
            for (var j = i * i; j < num; j += i) {
                numList[j] = false;
            }
        }
    }

    for (var k = 2; k < num; k++) {
        if (numList[k]) {
            output.push(k);
        }
    }
    var sum = output.reduce((acc, cur) => acc + cur, 0);
    console.log(output);
    return sum;
};

Pseudocode obtained from: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 伪代码来自: https//en.wikipedia.org/wiki/Sieve_of_Eratosthenes

There's nothing wrong with your code. 您的代码没有任何问题。 It returns the sum of primes less than num , and the sum of primes less than 977 is 72179. Your expected answer of 73156 is the sum of primes less than or equal to 977. The difference is 977 because 977 is prime. 它返回小于num的素数之和,小于977的素数之和为72179.您对73156的预期答案是小于或等于 977的素数之和。差值为977,因为977是素数。

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

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