WAP to find the factorial of a given number
Objective
Write a C++ program to find the factorial of a given number.
Algorithm / Approach
- Read an integer
nfrom the user. - Initialize a
res(result) variable to 1. - Start a
forloop withi = nand decrementidown to 2 (i--). - Multiply
resbyi:res = res * i. - Print the result.
main.cpp
include< iostream>
us#ing namespace std;
int main() {
int n, res = 1;
cout<<"Enter a number ";
cin>>n;
for(int i=n; i>=2;i--) {
res = res*i;
}
cout<<"Result = "<< res<< endl;
return 0;
}
Expected Output
Enter a number 5 Result = 120
Explanation of the Program
- The factorial of a number N (written as N!) is the product of all positive integers less than or equal to N.
- We can run the loop backwards (from N down to 2) or forwards (from 1 up to N). Both calculate the exact same mathematical product. Also, note that we initialize
resto 1, not 0, because multiplying by 0 would destroy the calculation.
Complexity
Time Complexity
O(n) - The loop runs N times.
Space Complexity
O(1)