简体   繁体   中英

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

I need to do factorials for quite large numbers that will take some time. How can I determine how far through working out the factorial the function is?

(This answer is a spin-off of the discussion of modular factorials in the comments.)

Computing modular factorials by taking mods at each step is definitely the way to go and can be used in conjunction with Wilsons's Theorem to give an (impractical) way to test for primes:

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)

Typical output:

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

Using the ipython utility 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

....can you memoize? At all?

You could do something like this:

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

Typical output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM