Factorial of a large number in python

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

    The slowdown in caused by a quadradic effect: as n gets larger you have to do more multiplications, but you also have to multiply larger numbers.

    Finding a better algorithm won't be easy. You can try to exploit symmetries (as in FFT). It could also well pay to do multiplications in a different order, with intermediate results, such that you end up with multiplying only a few very big numbers at the end, but I haven't thought that to the end. In any case, you will have to find a law to exploit.

    Look here for further inspiration.

提交回复
热议问题