[英]Python: Recursion depth exceeded error
我重新编写程序以获得大质数。 现在它工作正常,除了在打印完所有输出后,我在最后得到大量的红色短语。 有人可以告诉我为什么吗?
结果是输出是:
(100000939.0, 'is prime')
(100000963.0, 'is prime')
(100000969.0, 'is prime')
错误是
Traceback (most recent call last):
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 48, in <module>
loopfunction()
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 35, in loopfunction
loopfunction()
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 35, in loopfunction
loopfunction()
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 35, in loopfunction
loopfunction()
...(many lines of it, the int ends with:)
File "C:/Users/Marcela/Documents/Prime numbers to 100", line 13, in loopfunction
while index <= 200000000.0:
RuntimeError: maximum recursion depth exceeded in cmp
这是脚本:
from __future__ import division
import sys
index=100000000.0
checker=2.0
def loopfunction():
global index
global checker
checker=2
while index <= 200000000.0:
if index>=200000001:
sys.exit(1)
while checker<=14473.0:
div = index/checker
roundiv=round(index/checker, 0)
if index == 1:
print (index, "is prime")
checker=2
index=index+1
loopfunction()
if checker == index:
print (index, "is prime")
checker=2
index=index+1
loopfunction()
if roundiv==div:
checker=2
index=index+1
loopfunction()
if checker==14473.0:
print (index, "is prime")
checker=2
index=index+1
loopfunction()
checker = checker +1
loopfunction()
您可以通过简单地不递归来修复递归限制问题。 您的代码已经具有您需要的循环。
只要改变到呼叫loopfunction()
在各个if语句来break
。
虽然这就是使代码运行所需的全部内容,但我注意到你的if语句中有一些是不必要的(无论是循环条件多余,还是根本无法命中)。 你也在使用while
循环,其中for _ in range()
循环会更有意义。 这是代码的大大简化版本,重命名了一些内容以阐明其用途:
from math import sqrt
def primeFinder(start, end):
prime = True
for index in range(start, end):
for checker in range(2, int(sqrt(index))+1):
if index % checker == 0:
prime = False
break
if prime:
print("%d is prime" % index)
prime = True
primetest(100000000, 200000001)
这个版本仍然需要很长时间(可能是几个小时)。 如果你真的想测试一亿个素数值,你应该研究一个更好的算法,比如Eratosthenes的Sieve 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.