Finding the nth number of primes

倾然丶 夕夏残阳落幕 提交于 2020-01-25 07:39:25

问题


I can not figure out why this won't work. Please help me

from math import sqrt

pN = 0 
numPrimes = 0
num = 1

def checkPrime(x):
   '''Check\'s whether a number is a prime or not'''
   prime = True
   if(x==2):
      prime = True
   elif(x%2==0):
      prime=False
   else:
      root=int(sqrt(x))
      for i in range(3,root,2):
         if(x%i==0):
            prime=False
            break
   return prime

n = int(input("Find n number of primes. N being:"))

while( numPrimes != n ):
   if(  checkPrime( num ) == True ):
      numPrimes += 1
      pN = num
      print("{0}: {1}".format(numPrimes,pN))
   num += 1

print("Prime {0} is: {1}".format(n,pN))

回答1:


You need to change

root=int(sqrt(x))

into

root=int(sqrt(x))+1

(Take 9 for instance, int(sqrt(9)) is 3, and range(3, 3, 2) is [], and you do really want to test dividing by 3!).

Technically, 1 is not a prime either. Add

if(x<=1):
   prime = False

and you'll get the same result as http://www.rsok.com/~jrm/first100primes.html




回答2:


Differently from what @Braxton says in a comment, the Sieve of Eratosthenes algorithm can easily be adapted to generate unbounded primes (e.g. as a potentially-infinite generator, which can then be curtailed as desired e.g. by itertools.slict).

See this recipe for an unbounded Sieve in Python (and be sure to apply the enhancements shown in the comments, including mine;-) or see the same recipe as finally edited for the printed Cookbook here (unfortunately the discussion part is curtailed in this google books hit, but at least the Solution's code is all there;-).



来源:https://stackoverflow.com/questions/3030226/finding-the-nth-number-of-primes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!