Click here to Skip to main content
15,886,519 members
Articles / Programming Languages / C#

Calculate the Factorial of an Integer in C#

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

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
19 Oct 2011ARBebopKid
My preference for run-time speed is:long Factorial(int input){ if (input 1; input--) { if (long.MaxValue - answer < answer) throw new...
Please Sign up or sign in to vote.
4 Oct 2011George Swan
Recursion is a neat way of calculating a number's factorial but there is a danger of the stack overflowing when the number is large. The following is a simplified version of the original. It obviates the need for the if else statements within the where loop.int Factorial(int input){ int...
Please Sign up or sign in to vote.
4 Oct 2011Mohammad A Rahman
It could be done using Recursive Lambda Expression, for example,class Program{ static Func Factorial = x => x < 0 ? -1 : x == 1 || x == 0 ? 1 : x * Factorial(x - 1); static void Main(string[] args) { Console.WriteLine(Factorial(5)); }}(The code...
Please Sign up or sign in to vote.
18 Oct 2011Matthew Dennis
The System.Numeric.BigInteger class allows for calculating VERY LARGE values.I created a sample window form app to calculate the factorial of an input valueprivate void button1_Click(object sender, EventArgs e){ int inputValue; if (int.TryParse(this.textBox1.Text, out inputValue)...
Please Sign up or sign in to vote.
4 Oct 2011mcjohnson 6 alternatives  
Please Sign up or sign in to vote.
3 Oct 2011Anshul R
Use Recursion.int factorial(int n){ if(n<0) return -1; if(n==0 || n==1) return 1; return n * factorial(n-1);}

License

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


Written By
Architect
United States 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.

Comments and Discussions