我怎样才能计算出阶乘在 Python 中需要多长时间?

How can I work out how long a factorial will take in Python?

我需要对相当大的数字进行阶乘,这需要一些时间。如何确定函数的阶乘计算距离?

使用 ipython 实用程序 timeit:

In [2]: timeit math.factorial(10)
1000000 loops, best of 3: 238 ns per loop

In [3]: timeit math.factorial(100) 
100000 loops, best of 3: 2.43 µs per loop

In [4]: timeit math.factorial(1000)
10000 loops, best of 3: 114 µs per loop

In [5]: timeit math.factorial(10000)
100 loops, best of 3: 9.02 ms per loop

In [6]: timeit math.factorial(100000)
1 loops, best of 3: 517 ms per loop

..你能记住吗?有吗?

你可以这样做:

def factorial(n, displayProgress = False):
    p = 1
    for i in range(1,n+1):
        p *= i
        if displayProgress and i % 1000 == 0:
            print(round(100*i/n,1),'%', sep = '')
    return p

典型输出:

>>> print(len(str(factorial(10000,True))))
10.0%
20.0%
30.0%
40.0%
50.0%
60.0%
70.0%
80.0%
90.0%
100.0%
35660

(此答案是评论中对模阶乘的讨论的副产品。)

通过在每一步取 mod 来计算模阶乘绝对是可行的方法,并且可以与威尔逊定理结合使用以提供一种(不切实际的)测试素数的方法:

def modFact(k,n):
    #computes k! mod n
    p = 1
    for i in range(1,k+1):
        p = (p*i) % n
    return p

def isPrime(n):
    return n == 1+ modFact(n-1,n)

典型输出:

>>> for i in range(2,20): print(i,isPrime(i))

2 True
3 True
4 False
5 True
6 False
7 True
8 False
9 False
10 False
11 True
12 False
13 True
14 False
15 False
16 False
17 True
18 False
19 True
>>> isPrime(531455)
False
>>> isPrime(531457)
True