簡體   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