Calculating factorial

Alex Martelli aleaxit at yahoo.com
Mon Dec 4 11:45:46 EST 2000


"Olli Rajala" <ollir at linuxfreak.com> wrote in message
news:3a2a9496.647995 at uutiset.nic.fi...
> Hi!
> I've learned a few time Python and programming.  I wrote a function
> that calculates a factorial of N and I was wondering if it's the best
> (I think it's not. =) way to do that. I'm glad to hear your comments.
>
> <script>
>
> def factorial(f):
>     result = 1
>     for number in range(1, f + 1):
>         result = result * number
>     return result
>
> print factorial(10)

It's not too bad, the main limit being that it
will only work for a *VERY* small f; you can
remedy that by changing the very first statement:
    result = 1L
*Now* it will work for decently-sized f.

Attempts to get more sophisticated, such as

def factorial(f):
    import operator
    return reduce(operator.mul, range(1,f+1), 1L)

will not necessarily bring happiness.  Measuring
1000 calls for f==13, on my machine this appears
substantially slower -- about 0.85 milliseconds
per call (net) vs 0.72 for your simple approach
(just modified to do the computations with longs).


I _think_ the only way to accelerate this quite
substantially is...:

import gmpy

def factorial(f):
    return gmpy.fac(f)

which gives me about 0.09 milliseconds per call
in the same situation.  But I guess this is sort
of cheating, since gmpy is a module I'm just now
developing (http://gmpy.sourceforge.net/) and it
'just happens' to have .fac (factorial) as one of
its built-in functions (I do enough combinatorial
arithmetic that I really appreciate these kinds
of order-of-magnitude speedups:-).


Alex






More information about the Python-list mailing list