Factorial of a Number in C++
Factorial in C++: 5! is 120. Use long long — 13! overflows int. 0! is 1.
1#include <iostream>2using namespace std;34int main() {5 int n;6 long long factorial = 1;78 cout << "Enter a positive integer: ";9 cin >> n;1011 if (n < 0) {12 cout << "Factorial is not defined for negative numbers" << endl;13 } else {14 for (int i = 1; i <= n; i++) {15 factorial *= i;16 }17 cout << "Factorial of " << n << " = " << factorial << endl;18 }1920 return 0;21}
Output
Enter a positive integer: 5 Factorial of 5 = 120
What's going on
n! in C++ is 1 × 2 × … × n. 5! is 120. That's the sample. 0! is 1. Negative n is not defined.
int n;
long long factorial = 1;
Start the product at 1, not 0. 0 * anything is 0, and you never recover.
Why long long: 13! is 6,227,020,800. That does not fit in a 32-bit int (~2.1 billion). long long holds through 20!. 21! overflows even that.
cin >> n;
Sample: 5.
if (n < 0)
Print that factorial isn't defined. Don't run the loop on -3.
for (int i = 1; i <= n; i++)
factorial *= i; (same as factorial = factorial * i)
Walk 5:
n == 0: the loop condition 1 <= 0 is false. factorial stays 1. That's 0!.
n == 1: one iteration, still 1.
Then cout << "Factorial of " << n << " = " << factorial. Sample: Factorial of 5 = 120.
A recursive fact(n) = n * fact(n-1) is the same math with a stack. Missing the n <= 1 base case is a crash, not a clever answer.