简体   繁体   English

Python:找到第n个质数

[英]Python: find the nth prime number

I'm trying to find the nth prime number using the sieve of erathostenes. 我正在尝试使用erathostenes的筛子找到第n个质数。 Yes, I saw similar posts, but I have a problem with this piece of code. 是的,我看到了类似的帖子,但是这段代码有问题。 I want to stop the algorithm once it finds the nth prime. 一旦找到第n个素数,我想停止该算法。 This is what I wrote: 这是我写的:

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)

It doesn't work though. 虽然不行。 At least not as I want to. 至少不是我想要的。 If I add return filter(None, sieve)[n-2] it works fine. 如果我添加返回过滤器(无,筛子)[n-2],它将正常工作。 But I want it to stop computing at the nth prime. 但是我希望它在第n个素数时停止计算。 This is the output instead: 这是输出:

2 3
3 5
4 7
5 11
None

While I would expect it to continue until: 虽然我希望它将持续到:

...
11 31 

If the function is able to calculate all the sieve up to the limit correctly, why does the output behave like that? 如果函数能够正确计算出所有筛子的数量 ,为什么输出会如此?

The Python break command breaks out of loops, not out of tests ( if - else ). Python break命令打破了循环,而不是超出了测试if - else )。 I get it to work by reworking the logic to eliminate the break command. 我通过重新设计逻辑以消除break命令来使其工作。 That is, 那是,

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

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

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