Python 中的阶乘函数 [英] Function for Factorial in Python
本文介绍了Python 中的阶乘函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 中计算一个整数的阶乘?
How do I go about computing a factorial of an integer in Python?
推荐答案
最简单的方法是使用 math.factorial
(在 Python 2.6 及更高版本中可用):
Easiest way is to use math.factorial
(available in Python 2.6 and above):
import math
math.factorial(1000)
如果您想/必须自己编写,可以使用迭代方法:
If you want/have to write it yourself, you can use an iterative approach:
def factorial(n):
fact = 1
for num in range(2, n + 1):
fact *= num
return fact
或递归方法:
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
请注意,阶乘函数仅针对正整数定义,因此您还应该检查 n >= 0
并且 isinstance(n, int)
.如果不是,则引发 ValueError
或 TypeError
分别.math.factorial
会为你解决这个问题.
Note that the factorial function is only defined for positive integers so you should also check that n >= 0
and that isinstance(n, int)
. If it's not, raise a ValueError
or a TypeError
respectively. math.factorial
will take care of this for you.
这篇关于Python 中的阶乘函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文