I can not figure out why this wo开发者_如何学编程n'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 (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;-).
精彩评论