C++ Program to Find Factorial Using Recursion
Last Updated :
08 Feb, 2024
The factorial of a number is denoted by “n!” and it is the product of all positive integers less than or equal to n. In this article, we will learn how to find the factorial of a number using recursion in C++.
Example
Input: 5
Output: Factorial of 5 is 120
Factorial Using Recursion in C++
The Factorial of the number is calculated as below:
n! = n × (n−1) × (n−2) × … × 2 × 1
To find factorial using the recursion approach follow the below approach:
- Define a function to calculate factorial recursively.
- Create a Base case – if n is 0 or 1, return 1.
- If n is not 0 or 1, return n multiplied by the factorial of (n-1).
C++ Program to Find Factorial Using Recursion
The below program finds a factorial of a given number using recursion.
C++
#include <iostream>
using namespace std;
long long factorial( int n)
{
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main()
{
int num = 5;
cout << "Factorial of " << num << " is "
<< factorial(num) << endl;
return 0;
}
|
Output
Factorial of 5 is 120
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...