[Tutor] how to handle big numbers

Peter Otten __peter__ at web.de
Sat Dec 10 11:09:58 CET 2011


surya k wrote:

> Finding factorial of 8 or 9 isn't big. If I would like to find factorial
> of 32327, how can I ?

gmpy is a library designed for working with large numbers. Compare:

>>> import time
>>> def bench(f, *args):
...     start = time.time()
...     try:
...             return f(*args)
...     finally:
...             print time.time() - start
...
>>> def fac(n):
...     f = 1
...     for i in xrange(1, n+1):
...             f *= i
...     return f
...
>>> x = bench(fac, 1000)
0.00276589393616
>>> x = bench(fac, 10000)
0.247038125992
>>> x = bench(fac, 30000)
1.40305805206
>>> import gmpy
>>> x = bench(gmpy.fac, 30000)
0.0243360996246
>>> x = bench(gmpy.fac, 10**6)
0.8047311306
>>> x.numdigits()
5565709

http://pypi.python.org/pypi/gmpy



More information about the Tutor mailing list