« Calculate Factorial for a given number
Problem
You are given an integer ‘N’. You have to print the value of Factorial of ‘N’. The Factorial of a number ‘N’ is defined as the product of all numbers from 1 to ‘N’.
For Example:
Consider if ‘N’ = 4, the Factorial of 4 will be the product of all numbers from 1 to 4, which is 1 * 2 * 3 * 4 = 24. Hence, the answer is 24.
Input Format:
Ane single integer ‘N’
Output Format:
A single integer representing factorial on
N``
Constraints:
1 <= N <= 100
Sample Input 1:
4
Sample Output 1:
24
Sample Input 2:
6
Sample Output 2:
720
Very Important:
1int factorial(int n)2{3 cout << "n: " << n << endl;4 // if (n == 0)5 // {6 // return 1;7 // }8 int smallOutput = factorial(n - 1);9 return n * smallOutput;10}
Above function gets called recursively infinite times. Each function instance is waiting for other function instances to finish up. So they are taking some memory(for example they are storing value of n
) in system. If we call the recursive function infinite times then at some point of time there won't be any more memory available. Then we will get segmentation fault.
Solution:
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int factorial(int n)15{16 if (n == 0)17 {18 return 1;19 }20 int smallOutput = factorial(n - 1);21 return n * smallOutput;22}2324int main()25{26 int n;27 cin >> n;28 int output = factorial(n);29 cout << output << endl;30 return 0;31}