Click here to Skip to main content
15,847,750 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Calculate the Factorial of an Integer in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
19 Oct 2011CPOL 12.3K   7
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)


Written By
Software Developer State of Arkansas & Zycron
United States United States
Bryan Lee learned to code on a RadioShack Color computer II.

Comments and Discussions

 
GeneralActually, this is not a joke. How can you check that a multi... Pin
YvesDaoust24-Oct-11 22:51
YvesDaoust24-Oct-11 22:51 
GeneralJust for the sake of being picky, how can you be sure that w... Pin
YvesDaoust24-Oct-11 22:45
YvesDaoust24-Oct-11 22:45 
GeneralUpdated with simplistic overflow detection. This works only... Pin
ARBebopKid19-Oct-11 5:16
ARBebopKid19-Oct-11 5:16 
GeneralJust demonstrating my preferred algorithm. And if long is 6... Pin
ARBebopKid19-Oct-11 4:21
ARBebopKid19-Oct-11 4:21 
GeneralShouldn't you add overflow detection ? (Doing it without the... Pin
YvesDaoust18-Oct-11 23:31
YvesDaoust18-Oct-11 23:31 
GeneralTrue, but I do not consider that a means of calculating Fact... Pin
ARBebopKid18-Oct-11 5:21
ARBebopKid18-Oct-11 5:21 
True, but I do not consider that a means of calculating Factorials. It is a mean of storing the results of the calculations and returning the answers.
GeneralAs regards speed, nothing beats Alternative 4. Pin
YvesDaoust17-Oct-11 21:34
YvesDaoust17-Oct-11 21:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.