内存错误(无基本情况的递归)

问题描述 投票:0回答:1

我正在尝试计算一个大数的阶乘,但遇到了

MemoryError
。我怎样才能优化我的代码。??

def factorial(n):
  """Calculates the factorial of a number."""
  if n == 0:
    return 1
  else:
    return n * factorial(n)

# Try calculating a large factorial
factorial(1000)
python debugging memory memory-management
1个回答
0
投票

这是在 Python 中计算阶乘的更正代码,解决了内存错误:

def factorial(n):
  """Calculates the factorial of a number."""
  if n == 1:  # Corrected base case (factorial of 1 is 1)
    return 1
  else:
    return n * factorial(n - 1)

# Example usage with a smaller input to avoid potential memory issues
result = factorial(5)
print(f"Factorial of 5: {result}")

在此版本中,基本情况是

n == 1
。当
n
达到 1 时,函数返回 1,停止递归。然后递归调用返回
n
n-1
的阶乘的乘积,最终计算原始输入
n
的阶乘。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.