C++ How To Calculate the Factorial of a Number
Calculate the Factorial of a Number
The factorial of a number is the number multiplied by all the whole numbers below it. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120:
Example
int n = 5;
long long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
cout << "Factorial of " << n << " is " << factorial;
You can also use recursion, a function that calls itself:
Example
long long factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
cout << "Factorial of 5 is " << factorial(5);
Explanation:
We use long long, because factorials grow very fast. The factorial of 20 is too large for an int.
In the recursive version, factorial(5) calls factorial(4), which calls factorial(3), and so on, until it reaches 1.