I\'ve been trying to make a factorial function in C++, and I just found that inputs which are greater than 10 are not calculated correctly. I tried C# but I faced the same probl
This is because factorials are big numbers and the don't fit in an int
variable. It overflows. If You use unsigned long long
instead of int
, You can compute greater factorials.
If the result doesn't need to be precise, You can use double as well. In the other case, You can implement the multiplication on arrays and You can compute as big factorials as You want.
In C/C++, I recommend the GMP library
And because you asked for C family languages: Java has a BigInteger
type which is also useful.
Reason for You problem in simple.In C++ biggest in Long Long int. it has range of ~10^18. so you can't store numbers greater than that. and 100! have 158 digits in it so there is no way you can store that number in C++/C unless you can use vector/Array
You are a new Programmer and you are using Only C++/C .
Then i will not recommend for using GMP library for programming purpose(Algorithm or Programming contest Purpose) unless you are programming for some software.
I think you can implement your own and use it.. I use this one for my own purpose in Programming contest and Algorithm problem.
// Shashank Jain
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#define LL long long int
using namespace std;
vector<int> fact;
void do_it(int num)
{
int temp,carry;
vector<int>:: iterator it;
carry=0;
for(it=fact.begin();it!=fact.end();it++)
{
temp=(*it)*num;
temp+=carry;
*it=temp%10;
carry=temp/10;
}
if(carry!=0)
{
while(carry>0)
{
temp=carry%10;
fact.push_back(temp);
carry/=10;
}
}
}
int main()
{
int num,i,l;
cin>>num; // enter number for which you want to get factorial
fact.push_back(1);
for(i=2;i<=num;i++)
do_it(i);
l=fact.size();
cout<<"The Length of factorial is: "<<l<<endl;
for(i=l-1;i>=0;i--)
{
cout<<fact[i];
}
cout<<endl;
return 0;
}
Running Code link On Ideone
This can easily get the factorial of 2000 in less than 1 sec. Or else You can use GMP library. But Those are not allowed for Programming Contest like Google Code jam or Facebook Hacker Cup. or topcoder or anyother standard programming contest
That's because int
is limited to 32 bits, and results of 10!
much beyond 10 will give you a bigger result. For larger values, you can get an approximate result using double
as the result. If you want more than about 16 digits precision, you need to use a multiprecision math library.
Using uint64_t
would allow a larger number, but still fairly limited.
Variables cannot hold an infinite number of values. On a 32-bit machine, the maximum value an int
can represent is 2^31-1, or 2147483647. You can use another type, such as unsigned int
, long
, unsigned long
, long long
, or the largest one, unsigned long long
. Factorials are big numbers, and can easily overflow! If you want arbitrary precision, you should use a bignum library, such as GNU GMP.