Python math 模块

Python math.factorial() 函数用于计算阶乘 n!。

语法

math.factorial(n)

参数

n:非负整数。

返回值

返回 n 的阶乘(int)。n 为负数或非整数抛 ValueError

示例

import math

print(math.factorial(5))     # 120,5*4*3*2*1
print(math.factorial(0))     # 1
print(math.factorial(3))     # 6

# 组合数 C(n, k)
def comb(n, k):
    return math.factorial(n) // (math.factorial(k) * math.factorial(n - k))

print(comb(5, 2))            # 10

输出:

120
1
6
10

注意事项

参数必须是非负整数,否则抛 ValueError。结果增长极快,20! 就超 2.4e18。