Reputation: 411
So I am trying to find 6th prime number, and the while loop in getPrime is not working properly. It is supposed to end when count is bigger than num, but it doesn't. It'd be great if you could help me find out why.
import math
def isPrime(num):
if num == 1:
return False
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num % i == 0:
return False
return True
def getPrime(num):
count = 1
while count < num:
for i in range(1, 20):
#print "check"
if isPrime(i):
print "prime", i
count += 1
print "count", count
else:
continue
print i
return i
getPrime(6)
Upvotes: 1
Views: 3398
Reputation: 10379
Simplify getPrime, there is no need for a while loop:
def getPrime(num, r):
gen = (i for i in r if isPrime(i))
primes = zip(*zip(range(num), gen))[1]
return primes[num-1] if len(primes) >= num else None
>>> print getPrime(6, xrange(1, 20))
13
>>> print getPrime(6, xrange(100, 500))
127
Upvotes: 0
Reputation: 7377
You're only checking the value of count at the end of the for loop so you will always end up with the full range of 1-20 being tested. Why is the range limited to 20?
You don't need a for loop at all. Use the while loop to keep finding primes until you have num
of them.
Try something like:
def getPrime(num):
count = 0
i = 1
highPrime = None
while count < num:
if isPrime(i):
count += 1
highPrime = i
i += 1
return highPrime
Upvotes: 0
Reputation: 1840
The reason is because your range statement is within the body of the while statement. In another language you might use a do... until statement, but in Python the way to do it is just to add a conditional break statement, e.g. I have corrected your code to:
def getPrime(num):
count = 1
for i in range(1, 20):
if count > num: break
if isPrime(i):
highestPrime = i
count += 1
return highestPrime
Upvotes: 2
Reputation: 28870
In the getPrime()
function, when isPrime(i)
returns False
, you are not incrementing the count
variable. So the while count < num
loop gets stuck at that point.
Update: Well, that was my first impression from looking at the code. But then I noticed the nested loop. So I could have misread what was going on.
What I recommend at this point is stepping through the code in a debugger so you can see for yourself what is happening. Do you have a Python debugger available?
You can answer almost any question like this yourself if you have a good debugger and know how to use it. Then you won't have to wait for your friends on Stack Overflow to take guesses about what's going wrong! :-)
Upvotes: 2