C++ Program to Find Factorial of a Number Using Dynamic Programming
Last Updated :
27 Feb, 2024
The Factorial of a number N can be defined as the product of numbers from 1 to the number N. More formally factorial of n can be defined by function,
[Tex]f(n) = 1 \times 2 \times 3 \times… \ n[/Tex]
In this article, we will learn how to find the factorial of a number using dynamic programming in C++.
Example:
Input:
n = 5
Output:
Factorial = 120
Factorial of a Number Using Dynamic Programming in C++
To find the factorial of the number N using dynamic programming, we will first define an array of size (N + 1) and then define dp[0]=1 and dp[1]=1 . After that, we will fill the dp array by multiplying the current index by the value in dp array at previous index.
Approach
- Define an array named as dp.
- Declare dp[0]=1 abd dp[1]=1.
- Start a loop from 1 to N.
- In each iteration of the loop, do dp[i]=i*dp[i-1].
- The value at dp[N] will correspond to the factorial of number N.
C++ Program to Find the Factorial of a Number Using Dynamic Programming
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int num = 5;
vector< long long > factorial(num + 1);
factorial[0] = 1;
for ( int i = 1; i <= num; i++) {
factorial[i] = i * factorial[i - 1];
}
cout << "Factorial of " << num
<< " is: " << factorial[num] << endl;
return 0;
}
|
OutputFactorial of 5 is: 120
Time complexity: O(N)
Space complexity: O(N)
This method is efficient for large numbers or when the factorial function is called multiple times.
Share your thoughts in the comments
Please Login to comment...