Calculate factorials in C#

后端 未结 10 1793
日久生厌
日久生厌 2020-12-10 12:10

How can you calculate large factorials using C#? Windows calculator in Win 7 overflows at Factorial (3500). As a programming and mathematical question I am interested in kno

相关标签:
10条回答
  • 2020-12-10 12:22

    Have you looked at System.Numerics.BigInteger?

    0 讨论(0)
  • 2020-12-10 12:27

    Using System.Numerics BigInteger

    var bi = new BigInteger(1);
    var factorial = 171;
    for (var i = 1; i <= factorial; i++)
    {
        bi *= i;
    }
    

    will be calculated to

    1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000

    For 50000! it takes a couple seconds to calculate but it seems to work and the result is a 213237 digit number and that's also what Wolfram says.

    0 讨论(0)
  • 2020-12-10 12:31

    Have a look at the BigInteger structure:

    http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx

    Maybe this can help you implement this functionality.

    CodeProject has an implementation for older versions of the framework at http://www.codeproject.com/KB/cs/biginteger.aspx.

    0 讨论(0)
  • 2020-12-10 12:33

    Since they don't give you the result down to the last digit, they may be "cheating" using some approximation. Check out http://mathworld.wolfram.com/StirlingsApproximation.html Using Stirling's formula you can calculate (an approximation of) the factorial of n in logn time. Of course, they might as well have a dictionary with pre-calculated values of factorial(n) for every n up to one million, making the calculator show the result extremely fast.

    0 讨论(0)
提交回复
热议问题