Reputation: 23
I have the following C++ code to find factorial of a number:
#include <iostream>
using namespace std;
int factorial(int n){
if (n<=1)
{return 1;
}
return n*factorial(n-1);
}
int main()
{
int a;
cout<<"Enter a no: ";
cin>>a;
cout<<"The value of "<<a<<"! is "<<factorial(a);
return 0;
}
It works fine for values upto 12! But show wrong values above it. e.g. -- 20! is showing -2102132736 ( a negative no)
,for some big values like 50! show 0.
What could be the probable reason ???
Upvotes: 1
Views: 519
Reputation: 234715
Although formally the behaviour on overflowing an int
is undefined, modulo arithmetic on a number that's a power of 2 is a common treatment.
A number like 50! has as its many factors a large power of 2. This accounts for the zeros you are getting as output.
The solution is to use an arbitrary precision integer library. There's a good one in Boost.
Upvotes: 1