Factorials of large numbers
Given an integer N, find its factorial.
Example 1:
Input: N = 5
Output: 120
Explanation : 5! = 1*2*3*4*5 = 120
Example 2:
Input: N = 10
Output: 3628800
Explanation :
10! = 1*2*3*4*5*6*7*8*9*10 = 3628800
Example 3:
Input: N = 30
Output: .
Explanation :
30! =
Note: Factorials of can't be stored even in a long long variable. Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle big integers, but we need to write additional code in C/C++ to handle huge values.
We recommend solving this challenge using BigIntegers.
c++ implementation:
int multiply(int x,int a[],int size)
{
int carry=0;
for(int i=0;i<size;i++)
{
int p=(a[i]*x)+carry;
a[i]=p%10;
carry=p/10;
}
while(carry)
{
a[size]=carry%10;
carry=carry/10;
size=size+1;
}
return size;
}
void extraLongFactorials(int n)
{
int a[10000];
a[0]=1;
int size=1;
for(int i=2;i<=n;i++)
{
size=multiply(i,a,size);
}
for(int i=size-1;i>=0;i--)
cout<<a[i];
}
No comments