Why does this BigInteger value throw an exception? FROM#

I use BigIntegerin C#connection with the factorial function. The program has a lightning calculation of 5000!, But has an overflow error of 10,000 !. According to wolfram alpha , 10000! about

10000! = 2.8 × 10 ^ 35659

From what I can tell from this post , BigInteger is stored in an array int[]. If I interpret the type correctly int, it uses 4 bytes, which means 10000! uses about 4 x log10(2.8 x 10^35659) = 142636bytes where I use log10(n)(10-based log) as an approximation to the number of digits n. This is only 143 MB, but I still get the exception. Why is this happening?

using System;
using System.Numerics;

class Program
{
    static void Main()
    {
        BigInteger hugeFactorial = Calculations.Factorial(5000);
    }
}

class Calculations
{
    public static BigInteger Factorial(int n)
    {
        if (n == 1) return n;
        else return n*Factorial(n - 1);
    }
}
+4
3

Factorial stackoverflow . 10000! , . , .

+3

1 . . ( ):

TaskCompletionSource<BigInteger> tcs = new TaskCompletionSource<BigInteger>();
var t = new Thread(() => 
    {
        var res = Calculations.Factorial(10000);
        tcs.SetResult(res);
    }, 
    1024*1024*16 //16MB stack size
);
t.Start();
var result = await tcs.Task;
Console.Write(result);
+6

loopedcode, .

public static BigInteger Factorial(int n)
{
    BigInteger result = 1;
    for (int i = 2; i <= n; i++)
    {
        result *= i;
    }
    return result;
}

( ).

+6

Source: https://habr.com/ru/post/1616889/


All Articles