Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Calculate the Factorial of an Integer in C#

5.00/5 (1 vote)
19 Oct 2011CPOL 13.8K  
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:


C#
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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)