Factorial of a large number in python

后端 未结 9 756
灰色年华
灰色年华 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:19

    You can use the reduce function rather than explicit looping thus:

    >>> from functools import reduce
    >>> mul = int.__mul__
    >>> len(str(reduce(mul, range(2,100001), 1)))
    456574
    >>> 
    

    In Python 2 you need to use longs: long.__mul__, and len(str(reduce(mul, range(2L,100001L), 1L)))

提交回复
热议问题