簡體   English   中英

尋找第n個素數

[英]Finding the nth Prime

我正在嘗試創建一個將輸出第n個質數的算法。 我已經編寫了代碼,但是每當我運行它時,我都會得到第980個素數,何時應該輸出第1000個素數?

testNumber = 1
countPrimes = 0
testCounter = 2
isPrime = False
currentPrime = 0

while(countPrimes <= 1021): #runs for the first 1k primes
    testCounter=2
    isPrime = True
    if(testNumber%2 != 0): #checks if test number is odd
        while(testCounter*testCounter < testNumber): #counter^2 needs to be less than testNumber
            if(testNumber%testCounter == 0):
                isPrime = False
            testCounter = testCounter + 1
        if(isPrime==True):
            countPrimes = countPrimes + 1
            currentPrime = testNumber
    testNumber+=1

print currentPrime

問題在於您的代碼還將正整數(9、25、49等)作為素數。 那是因為您的代碼在到達數字的平方根之前就停止了除數測試。 要排除完美平方,您需要再檢查一個整數:

即代替:

while(testCounter*testCounter < testNumber): #counter^2 needs to be less than testNumber

嘗試這個:

while(testCounter*testCounter < testNumber + 1): #counter^2 needs to be less than testNumber

此外,您仍然會處於劣勢,因為您的代碼將0和1視為素數,而不將2視為素數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM