65.9K
CodeProject is changing. Read more.
Home

Calculate the Factorial of an Integer in C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Oct 12, 2011

CPOL
viewsIcon

13790

My preference for run-time speed is:long Factorial(int input){ if (input 1; input--) { if (long.MaxValue - answer < answer) throw new...

My preference for run-time speed is:

long Factorial(int input)
{
    if (input < 0)
        return -1;
    if (input < 2)
        return 1;
    long answer = input;
    for( ;input >1; input--)
    {
        if (long.MaxValue - answer < answer)
            throw new ArithmeticException();
        answer = input * answer;
    }

    return answer;
}