Python 求n次素数

Python 求n次素数,python,primes,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 = Tru

我正在尝试创建一个算法,它将输出第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
testNumber=1
countPrimes=0
测试计数器=2
isPrime=False
currentPrime=0

而(countPrimes问题在于,您的代码也将奇数完美平方(9、25、49等)计算为素数。这是因为您的代码在到达该数字的平方根之前停止测试可分性。要排除完美平方,您需要再检查一个整数:

即代替:

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

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

此外,您仍然会是一次性的,因为您的代码将0和1计为素数,而不将2计为素数。

逻辑完全被破坏。您对
testNumber
做过任何事情吗?在编码之前,请将逻辑写在纸上。@devnull感谢您指出我没有对testNumber做任何事情,我只是必须增加它,所以我没有这样做我想逻辑被破坏了。但是出于某种原因,它现在给我的是我要找的素数之前的素数?当我运行你的代码时,它会打印7919,这是第1000个素数。这里有什么问题吗?@Brionius抱歉,我应该指出。为了得到这个结果,while循环需要countprime我理解。请看下面我的答案。tha通常写的是
testCounter*testCounter