12,551,198 members (51,661 online)
Alternative Tip/Trick
alternative version

8.5K views
1 bookmarked
Posted

# Calculate the Factorial of an Integer in C#

, 18 Oct 2011 CPOL
 Rate this:
Or you could just go the other direction and cache the known results ahead of time. You're only looking at 13 numbers in all, so it is not a big memory hog to just store those known values inside of the method and be done with it.static uint Factorial(uint x){ if (x > 12) throw...
Or you could just go the other direction and cache the known results ahead of time. You're only looking at 13 numbers in all, so it is not a big memory hog to just store those known values inside of the method and be done with it.

```static uint Factorial(uint x)
{
if (x > 12)
throw new ArgumentException("Cannot calculate a factorial for numbers larger than 12");
return _factorials[x];
}
static readonly uint[] _factorials = new uint[13] { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600 };
```

Edit 10/11/2011: Corrected for goof on the last number (thanks Graham Toal).

## Share

 Software Developer (Senior) United States
Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.

So..If you're not moving forward, you're moving backwards.

## You may also be interested in...

 First Prev Next
 Re: I used an array of ints of 5 digit length as the product wou... Matthew Dennis18-Oct-11 13:55 Matthew Dennis 18-Oct-11 13:55
 Re: Did you just create your own data structure and perform the ... Andrew Rissing18-Oct-11 13:46 Andrew Rissing 18-Oct-11 13:46
 I hope you don't mind that I modified your tip. Unless I'm m... Qwertie18-Oct-11 8:02 Qwertie 18-Oct-11 8:02
 Re: I knew it would. I just didn't want to change the context o... Andrew Rissing18-Oct-11 13:42 Andrew Rissing 18-Oct-11 13:42
 Reason for my vote of 5 I like the idea a switch case can do... __erfan__17-Oct-11 22:02 __erfan__ 17-Oct-11 22:02
 Reason for my vote of 5 It's fast and simple. qsmart217-Oct-11 19:57 qsmart2 17-Oct-11 19:57
 Reason for my vote of 4 4 for the smartest solution; 1 point... Graham Toal11-Oct-11 10:00 Graham Toal 11-Oct-11 10:00
 Re: Corrected above. Thanks for the catch. Andrew Rissing11-Oct-11 10:19 Andrew Rissing 11-Oct-11 10:19
 How can an number ending on 00 suddenly end in 504 when mult... Graham Toal11-Oct-11 9:58 Graham Toal 11-Oct-11 9:58
 Reason for my vote of 5 That's the true way to do it. So man... YvesDaoust10-Oct-11 20:40 YvesDaoust 10-Oct-11 20:40
 Re: I had an assignment in university to calculate 72!, all 100 ... Matthew Dennis18-Oct-11 13:30 Matthew Dennis 18-Oct-11 13:30
 Reason for my vote of 5 Best way to dodge a buffer overflow ... tamcntt19854-Oct-11 15:50 tamcntt1985 4-Oct-11 15:50
 Last Visit: 31-Dec-99 18:00     Last Update: 23-Oct-16 19:05 Refresh 1