找到python中阶乘的最佳方法?

cod*_*ter 3 python factorial

我正在研究阶乘的速度.但我只使用两种方式,

import timeit

def fact(N):
    B = N
    while N > 1:
        B = B * (N-1)
        N = N-1
    return B

def fact1(N):
    B = 1
    for i in range(1, N+1):
        B = B * i
    return B


print timeit.timeit('fact(5)', setup="from __main__ import fact"), fact(5)
print timeit.timeit('fact1(5)', setup="from __main__ import fact1"), fact1(5)
Run Code Online (Sandbox Code Playgroud)

这是输出,

0.540276050568 120
0.654400110245 120
Run Code Online (Sandbox Code Playgroud)

从上面的代码我发现,

  1. 虽然花费的时间少于

我的问题是,

是在python中找到阶乘的最佳方法吗?

mgi*_*son 12

如果您正在寻找最好的,为什么不使用数学模块中提供的?

>>> import math
>>> math.factorial
<built-in function factorial>
>>> math.factorial(10)
3628800
Run Code Online (Sandbox Code Playgroud)

并对我机器上的时间进行比较:

>>> print timeit.timeit('fact(5)', setup="from __main__ import fact"), fact(5)
0.840167045593 120
>>> print timeit.timeit('fact1(5)', setup="from __main__ import fact1"), fact1(5)
1.04350399971 120
>>> print timeit.timeit('factorial(5)', setup="from math import factorial")
0.149857997894
Run Code Online (Sandbox Code Playgroud)

我们看到内置版比你提出的任何纯python变种要好得多.