簡體   English   中英

如何計算階乘在 Python 中需要多長時間?

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

我需要對相當大的數字進行階乘,這需要一些時間。 如何通過計算函數的階乘來確定多遠?

(這個答案是評論中對模階乘討論的衍生。)

通過在每一步采用 mods 來計算模階乘絕對是可行的方法,並且可以與威爾遜定理結合使用以提供一種(不切實際的)測試素數的方法:

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

使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM