Factorial of 200 have 375 digits. It is not possible to store these values to data types(int , long long int) in C++.
In this code we are going to use a vector(dynamic memoory allocation) to store the factorial of a number. we have used two function "multiply()" and "factorial". The function "factorial()" calls the function "multiply" and calculate the factorial of the number and store in the vector named "temp". Now stored value "temp" are in reverse order of required output so we reverse the vector using reverse function. Now we return "temp" that gets stored in value "a" . At last by using for loop we print the element in a (which is our required factorial of number).
CODE:
#include<bits/stdc++.h>
using namespace std;
void multiply(int x, vector&temp)
{
int carry = 0;
for (int i=0; i<temp.size(); i++)
{
int product = temp[i] * x + carry;
temp[i] = product % 10;
carry=product/10;
}
while(carry)
{
temp.push_back(carry%10);
carry =carry/10;
}
}
vectorfactorial(int N){
vectortemp;
temp.push_back(1);
int size=1;
for(int x=2;x<=N;x++)
multiply(x, temp);
reverse(temp.begin(),temp.end());
return temp;
}
int main()
{long long int t;
cout<<"Enter the bigger number whose factorial is to be calculated \n";
cin>>t;
vector a;
a=factorial(t);
for(int i=0;i<a.size();i++)
{
cout<<a[i];
}
return 0;
}
Submitted by AMAN KUMAR PANDEY (amanpandey)
Download packets of source code on Coders Packet
Comments