The factorial of a number is the product of all the integers from 1 up to that number. The factorial can only be defined for positive integers.
The factorial of a negative number doesn't exist. And the factorial of 0 is 1.
For example,
The factorial of a positive number n, say 5
, is denoted by 5!
and is given by:
5! = 1 * 2 * 3 * 4 * 5 = 120
So, the Mathematical logic for factorial is:
n! = 1 * 2 * 3 * ... * n
n! = 1 if n = 0 or n = 1
In this program below, the user is asked to enter a positive integer. Then the factorial of that number is computed and displayed on the screen.
Example: Find Factorial of a given number
#include <iostream>
using namespace std;
int main() {
int n;
long double factorial = 1.0;
cout << "Enter a positive integer: ";
cin >> n;
if (n < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
}
return 0;
}
Output
Enter a positive integer: 12 Factorial of 12 = 479001600
In this program, we take a positive integer from the user and compute the factorial using for
loop. We print an error message if the user enters a negative number.
We declare the type of factorial variable as long double
since the factorial of a number may be very large.
When the user enters a positive integer (say 4
), for
loop is executed and computes the factorial. The value of i is initially 1
.
The program runs until the statement i <= n
becomes false
. This prints Factorial of 4 = 24 on the screen. Here’s how the program executes when n = 4
.
i <= 4 | fact *= i |
---|---|
1 <= 4 | fact = 1 * 1 = 1 |
2 <= 4 | fact = 1 * 2 = 2 |
3 <= 4 | fact = 2 * 3 = 6 |
4 <= 4 | fact = 6 * 4 = 24 |
5 <= 4 | Loop terminates. |
This program can calculate the factorial only up to 1754
or some integer value close to it. Beyond that, the program can no longer calculate the factorial as the results exceed the capacity of the factorial variable.