Search code examples
c#stack-overflowlong-integerfactorial

Saving factorial in long integer


I am using the following code to get the Factorial, but it seems to be limited for me.

private Int64 GetFactorial(Int64 value)
{
    if (value <= 1)
    {
        return 1;
    }
    return value * GetFactorial(value - 1);
}

But it seems to only allow the values upto 65 on 66th value, it provides a 0 as a result and the result is negative too if the value is 65 or near. What can I do to allow more values to work with, and get result with having the System.StackOverflowException?


Solution

  • You may want to check out the BigInteger struct, as it allows integers of an arbitrarily-large size: http://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx