Cannot calculate factorials bigger than 20! ! How to do so?

后端 未结 7 473
清歌不尽
清歌不尽 2020-12-03 08:16

I am using unsigned long long integer format in order to calculate big factorials. However my code fails at some point can you have a look at it? Actually it is part of a la

7条回答
  •  一整个雨季
    2020-12-03 08:46

    Indeed:

    2^64 = 18446744073709551616
    21!  = 51090942171709440000
    20!  =  2432902008176640000
    

    By the way, to calculate the result of a series (e.g., Taylor) you should not calculate each term separately; this will definitely bring you problems such as this one. Instead, try to calculate each term by reusing the previous one.

    For example, the Taylor series for cos requires the summation of terms like:

    (-1)^i * (x^(2*i)) / (2i)!
    

    It is easy to see that each term can be calculated easily from the previous one:

    newterm = - oldterm * x^2 / ((2i+1)*(2i+2))
    

    So, I believe that you don't need to calculate large factorials, for what you're trying to do. On the other hand, if you need to, you'll have to use a library for big numbers, such as gmp.

提交回复
热议问题