views:

222

answers:

2

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))
+5  A: 

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

aioobe
Nice answer. Just modify the condition to be: if(x<=1)
AraK
good point :) .
aioobe
that worked perfectly! thank you
Braxton Smith
+1  A: 

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

Alex Martelli
Thank you! I obviously have a lot to learn, but that was tremendously helpful
Braxton Smith
@Braxton, you're welcome!
Alex Martelli