Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorial of a large number in python

Here's my approach to factorials:

def factorial(n):
    '''Returns factorial of n'''
    r = 1
    for i in range(1, n + 1):
        r *= i
    return r

I think it's pretty straightforward, though I guess you could make something more efficient, because it takes ages for large numbers like 100000. My question is, is there? math.factorial() is no good either, it takes roughly the same amount of time.

like image 853
Juan José Castro Avatar asked May 01 '13 20:05

Juan José Castro


1 Answers

Factorials get very large, so it is often better to deal with logarithms of the number.

Many languages have an lgamma library function which computes the natural logarithm of the factorial of n-1.

This means that you can compute the natural logarithm of factorial(n) via lgamma(n+1).

You can divide by log10 to turn this into a base 10 logarithm.

So if you just want the number of digits, then this Python code will give the answer immediately:

from math import *
print ceil(lgamma(100000+1)/log(10))
like image 73
Peter de Rivaz Avatar answered Sep 24 '22 22:09

Peter de Rivaz