Click here to Skip to main content
12,455,517 members (64,444 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.3K views
Posted

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.

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralActually, this is not a joke. How can you check that a multi... Pin
YvesDaoust24-Oct-11 21:51
memberYvesDaoust24-Oct-11 21:51 
GeneralJust for the sake of being picky, how can you be sure that w... Pin
YvesDaoust24-Oct-11 21:45
memberYvesDaoust24-Oct-11 21:45 
GeneralUpdated with simplistic overflow detection. This works only... Pin
USABebopKid19-Oct-11 4:16
memberUSABebopKid19-Oct-11 4:16 
GeneralJust demonstrating my preferred algorithm. And if long is 6... Pin
USABebopKid19-Oct-11 3:21
memberUSABebopKid19-Oct-11 3:21 
GeneralShouldn't you add overflow detection ? (Doing it without the... Pin
YvesDaoust18-Oct-11 22:31
memberYvesDaoust18-Oct-11 22:31 
GeneralTrue, but I do not consider that a means of calculating Fact... Pin
USABebopKid18-Oct-11 4:21
memberUSABebopKid18-Oct-11 4:21 
GeneralAs regards speed, nothing beats Alternative 4. Pin
YvesDaoust17-Oct-11 20:34
memberYvesDaoust17-Oct-11 20: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.

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