Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

Calculate the Factorial of an Integer in C#

, 19 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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;
}

License

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

Share

About the Author

ARBebopKid
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... PinmemberYvesDaoust24-Oct-11 22:51 
GeneralJust for the sake of being picky, how can you be sure that w... PinmemberYvesDaoust24-Oct-11 22:45 
GeneralUpdated with simplistic overflow detection. This works only... PinmemberUSABebopKid19-Oct-11 5:16 
GeneralJust demonstrating my preferred algorithm. And if long is 6... PinmemberUSABebopKid19-Oct-11 4:21 
GeneralShouldn't you add overflow detection ? (Doing it without the... PinmemberYvesDaoust18-Oct-11 23:31 
GeneralTrue, but I do not consider that a means of calculating Fact... PinmemberUSABebopKid18-Oct-11 5:21 
GeneralAs regards speed, nothing beats Alternative 4. PinmemberYvesDaoust17-Oct-11 21:34 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 19 Oct 2011
Article Copyright 2011 by ARBebopKid
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid