繁体   English   中英

Python:找到第n个质数

[英]Python: find the nth prime number

我正在尝试使用erathostenes的筛子找到第n个质数。 是的,我看到了类似的帖子,但是这段代码有问题。 一旦找到第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)

虽然不行。 至少不是我想要的。 如果我添加返回过滤器(无,筛子)[n-2],它将正常工作。 但是我希望它在第n个素数时停止计算。 这是输出:

2 3
3 5
4 7
5 11
None

虽然我希望它将持续到:

...
11 31 

如果函数能够正确计算出所有筛子的数量 ,为什么输出会如此?

Python break命令打破了循环,而不是超出了测试if - else )。 我通过重新设计逻辑以消除break命令来使其工作。 那是,

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

暂无
暂无

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

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