简体   繁体   中英

Finding the nth number of primes

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))

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

Differently from what @Braxton says in a comment, the Sieve of Eratosthenes algorithm can easily be adapted to generate unbounded primes (eg as a potentially-infinite generator, which can then be curtailed as desired eg 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;-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM