Given a large number N, the task is to find its factorial using recursion. Since the factorial of large numbers can exceed standard integer limits, the result is stored digit by digit.
- Recursion reduces the problem to calculating (N - 1)!.
- A vector is used to store and multiply the digits of the large factorial.
Illustration
Input : N = 100
Output : 933262154439441526816992388562667004-907159682643816214685929638952175999-932299156089414639761565182862536979-208272237582511852109168640000000000-00000000000000Input : N = 50
Output : 3041409320171337804361260816606476884-4377641568960512000000000000
Approach
- Store the factorial result as individual digits in a vector.
- Use recursion to calculate the factorial from N down to 1.
- Multiply each digit by the current number and maintain the carry.
- Store the resulting digits back in the vector.
- Print the digits in reverse order to obtain the factorial.
#include <bits/stdc++.h>
using namespace std;
// MUltiply the number x with the number
// represented by res array
vector<int> multiply(long int n, vector<int> digits)
{
// Initialize carry
long int carry = 0;
// One by one multiply n with
// individual digits of res[]
for (long int i = 0; i < digits.size(); i++) {
long int result
= digits[i] * n + carry;
// Store last digit of 'prod' in res[]
digits[i] = result % 10;
// Put rest in carry
carry = result / 10;
}
// Put carry in res and increase result size
while (carry) {
digits.push_back(carry % 10);
carry = carry / 10;
}
return digits;
}
// Function to recursively calculate the
// factorial of a large number
vector<int> factorialRecursiveAlgorithm(
long int n)
{
if (n <= 2) {
return multiply(n, { 1 });
}
return multiply(
n, factorialRecursiveAlgorithm(n - 1));
}
// Driver Code
int main()
{
long int n = 50;
vector<int> result
= factorialRecursiveAlgorithm(n);
for (long int i = result.size() - 1; i >= 0; i--) {
cout << result[i];
}
cout << "\n";
return 0;
}
Output
30414093201713378043612608166064768844377641568960512000000000000
Explanation: The recursive function first calculates (N - 1)! and then multiplies it by N. Since the result may contain more digits than standard integer types can store, the vector stores one digit at each position, while carry handles values exceeding a single digit.