[英]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:通过在每一步采用 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)
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
:使用 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
....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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.