Python分区问题超过最大递归深度
我创建了一个递归函数,以计算在(启动,结束)范围内N范围内的N总数。该功能适用于较小的数字,除非它们开始变得更大。 start = 1,结束= 10 ** 12-1给我一个错误,说超过了最大递归深度。我如何修复我的代码以停止此错误:
def count(start, end, n, tot=0):
if start > end:
return tot
else:
if start % n == 0:
tot += 1
return count(start + 1, end, n, tot)
start = 1
end = 10**12 - 1
n = 5
print(count(start, end, n))
I have created a recursive function to calculate the total numbers divisible by n within a range of (start,end). The function works for smaller numbers except when they start getting larger for ex. start=1 and end=10**12 - 1 gives me an error saying that the maximum recursion depth has been exceeded. How do I fix my code to stop this error:
def count(start, end, n, tot=0):
if start > end:
return tot
else:
if start % n == 0:
tot += 1
return count(start + 1, end, n, tot)
start = 1
end = 10**12 - 1
n = 5
print(count(start, end, n))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过简单的算术解决此问题。考虑
(3,18)
(包含)和n
5
之类的范围,实际关注范围来自5
to15
(由于5
5 5 或以上 15 。您可以将rown
和end
值绕到这样的新端点:您需要做的是只计算
5
的值15
(3)您可以从新的结束
中减去新的start
,由n
划分并添加1 IE可以简化,从而
总共您的功能变为:
You can solve this problem with simple arithmetic. Thinking about a range such as
(3, 18)
(inclusive) and ann
of5
, the actual range of interest is from5
to15
(since there are no multiples of5
below5
or above15
. You can round thestart
andend
values to the new endpoints like this:What you need to do then is just count the values from
5
to15
(3) which you can do subtracting the newstart
from the newend
, dividing byn
and adding 1 i.e.which can be simplified to
So in total your function becomes:
两个分。
Two points.