You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归函数sommeRec传入大数值触发RecursionError的排查与解决

递归深度超限问题的原因与解决办法

问题原因

Python默认给递归调用设了深度上限(通常为1000),你的sommeRec函数计算到n=2000时,需要递归调用2000次,直接超过了这个限制,因此触发RecursionError。

解决方法

1. 临时调大递归深度上限

你可以用sys模块修改递归深度的最大值,但这种方法有风险——调得太大可能导致操作系统栈溢出,直接崩程序,仅适合临时测试:

import sys
import time

def sommeRec(n):
    if n == 0:
       return 0
    elif n > 0:
        return sommeRec(n-1) + n

def tempsExecution2(n,f):
    start = time.time()
    f(n)               
    end = time.time()
    return end - start

# 把递归深度上限调到2001(比需要的调用次数多1即可)
sys.setrecursionlimit(2001)
print("le temps d'exe de sommeRec est: ")
print(tempsExecution2(2000, sommeRec))  

2. 改用迭代实现(推荐)

迭代没有递归深度限制,能稳定处理超大数值的运算:

import time

def sommeIter(n):
    total = 0
    for i in range(n + 1):
        total += i
    return total

def tempsExecution2(n,f):
    start = time.time()
    f(n)               
    end = time.time()
    return end - start

print("le temps d'exe de sommeIter est: ")
print(tempsExecution2(2000, sommeIter))
print(tempsExecution2(100000, sommeIter)) # 轻松处理更大的n

3. 使用数学公式(效率最高)

如果只是计算1到n的和,直接用等差数列求和公式n*(n+1)//2,时间复杂度为O(1),完全没有运算量限制:

import time

def sommeFormule(n):
    return n * (n + 1) // 2

def tempsExecution2(n,f):
    start = time.time()
    f(n)               
    end = time.time()
    return end - start

print("le temps d'exe de sommeFormule est: ")
print(tempsExecution2(2000, sommeFormule))
print(tempsExecution2(10**8, sommeFormule)) # 超大数值也能瞬间完成

小提醒

你的tempsExecution2函数中使用了time(),需要确保导入time模块,否则会触发NameError,建议写成time.time()更明确。

内容的提问来源于stack exchange,提问作者Axq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:50:24