I can\'t figure out why this python function returns None if it calls itself recursively.
It was part of my solution to a Project Euler problem. I have solved the p
You forgot to return a value when there is failure to find a prime:
for div in range(2,candidate//2,1):
if candidate % div == 0:
prime = False
print candidate, "is not prime - divisible by", div
return next_prime(candidate)
Recursion isn't really suitable here though. It isn't much more elegant than the simple iterative approach. Also, you could overflow the stack if you hit an area where there are lot of non-primes between two consecutive primes.
Notice that you are making recursive calls to the next_prime function, but not returning the value from it from the calling function.
Replace the lines:
print candidate, "is not prime - divisible by", div
next_prime(candidate)
with
print candidate, "is not prime - divisible by", div
return next_prime(candidate)
As others have said, this is not really the place for recursion. Here is an example using iteration. I've also defined another function which tests the primality of an integer - I think this makes the code simpler.
def is_prime(n):
"""Return True if n is prime."""
for i in xrange(2, n//2):
if n%i == 0:
return False
return True
def next_prime(n):
"""Returns the next prime number after n."""
if n % 2 == 0:
candidate = n + 1
else:
candidate = n + 2
while not is_prime(candidate):
candidate += 2
return candidate
if __name__ == '__main__':
n = 896576
print next_prime(n)