C# How To Calculate the Factorial of a Number
Factorial of a Number
The factorial of a number is the number multiplied by all the whole numbers below it, down to 1. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120:
Example
int n = 5;
long factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine("Factorial of " + n + " is " + factorial);
You can also use recursion, a method that calls itself:
Example
static long Factorial(int n)
{
if (n <= 1)
{
return 1;
}
return n * Factorial(n - 1);
}
static void Main(string[] args)
{
Console.WriteLine("Factorial of 5 is " + Factorial(5));
}
Explanation:
We use long, because factorials grow very fast. The factorial of 13 is already too large for an int.
In the second example, Factorial(5) calls Factorial(4), which calls Factorial(3), and so on, until it reaches 1.