【问题标题】:Python: find the nth prime numberPython:找到第 n 个素数
【发布时间】:2016-02-01 18:27:54
【问题描述】:

我正在尝试使用 Erathostenes 的筛子找到第 n 个素数。 是的,我看到了类似的帖子,但我对 this 段代码有疑问。 一旦找到第 n 个素数,我想停止算法。这是我写的:

def nth_prime(n):
    limit = 10**2
    pn = 1                     #keeps track of how many prime numbers we have found
    sieve = range(3, limit, 2)
    top = len(sieve)
    for si in sieve:
        if si:
            pn += 1
            print pn, si     #used to check while coding
            if pn == n:
                return si    #loop breaks when the nth prime is found
            else:   
                    bottom = (si*si - 3)/2
                    if bottom >= top:
                        break
                    sieve[bottom::si] = [0] * -((bottom-top)//si)   

print nth_prime(11)

但它不起作用。至少不像我想的那样。如果我添加 return filter(None, sieve)[n-2] 它工作正常。但我希望它在第 n 个素数时停止计算。 这是输出:

2 3
3 5
4 7
5 11
None

虽然我希望它会持续到:

...
11 31 

如果该函数能够正确计算所有筛子直到 limit,为什么输出会这样?

【问题讨论】:

    标签: python python-2.7 sieve-of-eratosthenes


    【解决方案1】:

    Python break 命令breaks out of loops, not out of tests (if-else)。我通过重新编写逻辑以消除break 命令来使其工作。也就是说,

        if bottom < top:
            sieve[bottom::si] = [0] * -((bottom-top)//si)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2013-01-22
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多