Factorial of a large number in python

后端 未结 9 832
灰色年华
灰色年华 2020-12-29 12:32

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         


        
9条回答
  •  失恋的感觉
    2020-12-29 13:12

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

提交回复
热议问题