【问题标题】:Why does my Sieve of Eratosthenes algorithm fail?为什么我的埃拉托色尼筛算法会失败?
【发布时间】:2015-04-09 12:53:51
【问题描述】:

是的,我知道 Eratosthenes 的筛子在标准库 Prime 类中,但我正在尝试实现自己以进行练习。

我按照维基百科上的描述逐字逐句:

用 Eratosthenes 的方法找出所有小于或等于给定整数 n 的素数: 1. 创建一个从 2 到 n 的连续整数列表:(2, 3, 4, ..., n)。
2. 最初,令 p 等于 2,即第一个素数。
3. 从 p 开始,以 p 为增量计数到 n 来枚举它的倍数,并在列表中标记它们(这些将是 2p、3p、4p、...;p 本身不应标记)。
4. 找出列表中第一个大于 p 且未标记的数。如果没有这样的号码,请停止。否则,现在让 p 等于这个新数(即下一个素数),然后从第 3 步开始重复。
5. 当算法终止时,列表中所有未标记的数字都是素数。

def sieve(n)
    # Create a list of consecutive integers from 2 through n.   
    list = [*2..n] # [2, 3, 4, 5, etc]
    p = 2 # Let p equal 2, the first prime number

    # Starting from p, enumerate its multiples by counting to n in in increments of p
    loop do
        p1 = p # We'll use this to count in increments, by adding the initial value of p to p each iteration
        until p >= n 
            p += p1
            list.delete(p) # Mark all multiples of p in the list
        end
        if list.find{|x| x > p}
            p = list.find{|x| x > p} # p now equals the first number greater than p in the list that is not marked (deleted)
        else
            return list
        end
    end
end

但是sieve(20)的输出是[2, 3, 5, 7, 9, 11, 13, 15, 17, 19],显然是2乘2。

我不知道为什么。

【问题讨论】:

    标签: ruby algorithm sieve-of-eratosthenes


    【解决方案1】:

    你正在改变 p,所以它在 list.find{|x| x > p} 中不是 2。也许你想把这部分代码改成list.find{|x| x > p1}

    【讨论】:

    • 该死,我什至没有想到。非常感谢 IvayloPetrov,修复了它。
    • @GreenTriangle:如果答案解决了您的问题,请接受。
    猜你喜欢
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 2018-07-03
    相关资源
    最近更新 更多