Python 阶乘
数学实例 012
题目
计算 n 的阶乘 n! = 1 × 2 × … × n,分别用循环、递归和标准库实现。
参考代码
import math
def fact_loop(n):
result = 1
for i in range(2, n + 1):
result *= i
return result
def fact_rec(n):
return 1 if n <= 1 else n * fact_rec(n - 1)
for n in [0, 5, 10, 20]:
print(f"{n}! = {fact_loop(n)} (递归:{fact_rec(n)},math:{math.factorial(n)})")
print("30! 共有", len(str(math.factorial(30))), "位数字")执行以上代码输出结果为:
0! = 1 (递归:1,math:1)
5! = 120 (递归:120,math:120)
10! = 3628800 (递归:3628800,math:3628800)
20! = 2432902008176640000 (递归:2432902008176640000,math:2432902008176640000)
30! 共有 33 位数字代码解析
Python 的整数没有大小上限,可以直接计算很大的阶乘。递归写法简洁,但递归深度默认限制在 1000 左右,计算很大的 n 时应使用循环或 math.factorial。