15,848,393 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

# Calculate the Factorial of an Integer in C#

Rate me:
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
Bryan Lee learned to code on a RadioShack Color computer II.

## Comments and Discussions

 First Prev Next
 Actually, this is not a joke. How can you check that a multi... YvesDaoust24-Oct-11 22:51 YvesDaoust 24-Oct-11 22:51
 Just for the sake of being picky, how can you be sure that w... YvesDaoust24-Oct-11 22:45 YvesDaoust 24-Oct-11 22:45
 Updated with simplistic overflow detection. This works only... ARBebopKid19-Oct-11 5:16 ARBebopKid 19-Oct-11 5:16
 Updated with simplistic overflow detection. This works only through 19! Alternative 7 using BigInteger is the way to go.
 Just demonstrating my preferred algorithm. And if long is 6... ARBebopKid19-Oct-11 4:21 ARBebopKid 19-Oct-11 4:21
 Shouldn't you add overflow detection ? (Doing it without the... YvesDaoust18-Oct-11 23:31 YvesDaoust 18-Oct-11 23:31
 True, but I do not consider that a means of calculating Fact... ARBebopKid18-Oct-11 5:21 ARBebopKid 18-Oct-11 5:21
 As regards speed, nothing beats Alternative 4. YvesDaoust17-Oct-11 21:34 YvesDaoust 17-Oct-11 21:34
 Last Visit: 31-Dec-99 19:00     Last Update: 28-Feb-24 14:06 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

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