找到第n个Prime

时间:2014-05-28 14:41:45

标签: python primes

我正在尝试创建一个输出第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

1 个答案:

答案 0 :(得分:1)

问题在于你的代码也将奇数正方形(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。