Coders Packet

Factorial of Large Number in C++

By AMAN KUMAR PANDEY

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;
}

 

 
 
Input : 200
 
Output : Factorial of given number is
788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000
 
 
Input : 70
Output : Factorial of given number is 11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000
 

Download project

Reviews Report

Submitted by AMAN KUMAR PANDEY (amanpandey)

Download packets of source code on Coders Packet