我无法弄清楚为什么这个
python函数返回None,如果它递归调用自己.
这是我解决项目欧拉问题的一部分.无论如何我已经以更好的方式解决了这个问题,但这仍然让我很烦,因为函数似乎工作正常 – 它似乎知道我想要返回的变量的值.
def next_prime(previous):
if previous % 2 == 0:
candidate = previous + 1
else:
candidate = previous + 2
print "trying", candidate
prime = True
for div in range(2,candidate//2,1):
if candidate % div == 0:
prime = False
print candidate, "is not prime - divisible by", div
next_prime(candidate)
break
if prime is True:
print candidate, "is prime"
#return candidate
last = 896576
print "After", last, ", the next prime is..."
next_prime(last)
这给出了:
After 896576 , the next prime is...
trying 896577
896577 is not prime - divisible by 3
trying 896579
896579 is not prime - divisible by 701
trying 896581
896581 is not prime - divisible by 7
trying 896583
896583 is not prime - divisible by 3
trying 896585
896585 is not prime - divisible by 5
trying 896587
896587 is prime
但是如果我取消注释return语句,它只返回一个值,如果第一次尝试是素数,否则它返回None.
最佳答案 当找不到素数时,您忘记返回值:
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)
这里递归并不适合.它比简单的迭代方法更优雅.此外,如果您遇到两个连续素数之间存在大量非素数的区域,您可能会溢出堆栈.