InterviewSolution
| 1. |
Write a program to print the factorial of a given input number. |
|
Answer» Example: Input: 5120In practically all interviews, factorial is one of the most frequently asked questions (INCLUDING developer interviews) Developer interviews place a greater emphasis on programming concepts such as dynamic programming, recursion, and so on, whereas Software Development Engineer in TEST interviews place a greater emphasis on handling edge scenarios such as max values, min values, negative values, and so on, and approach/efficiency becomes secondary. The following recursive formula can be used to calculate factorial. n! = n * (n-1)!n! = 1 if n = 0 or n = 1Code: #include <bits/stdc++.h>using namespace std;// function to find the factorial of given numberint findFactorial(unsigned int n){ if (n == 0) return 1; return n * factorial(n - 1);}int main(){ int number = 5; if(number < 0) { cout << "Negative numbers do not have factorial" << "\n"; return 0; } cout << "Factorial of " << number << " is " << findFactorial(number) << “\n”; return 0;}Output: Factorial of 5 is 120Explanation: |
|