This program is doing the factorial of a number and for some reason whenever i type in 13 i get an error......The Factorial of you number, 13,is:
terminate called after throwing an instance of 'int'
Abort trap....It works for 12 and lower but nothing above that. can someone please explain to me why?
Note:
13! = 6,227,020,800 so 13! > 500,000,000
12! = 479,001,600 so 12! <= 500,000,000
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main(int argc, char** argv)
{
...
try
{
factorial(fact);
cout << factorial(fact) << endl; //you invoke the method twice, hence you throw the int twice.
// you might want to store the result instead (see below)
}
catch (int over)
{
cerr << "ERROR: Overflow at n = " << over << "." << endl; exit(EXIT_FAILURE);
}
// cout << factorial(fact) << endl; //moved above
}
or
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main(int argc, char** argv)
{
...
int f = -1;
try
{
f = factorial(fact);
}
catch (int over)
{
cerr << "ERROR: Overflow at n = " << over << "." << endl; exit(EXIT_FAILURE);
}
if( f > 0 )
cout << f << endl;
}
Like said Mathhead200, you can't have 13! on int. Or at least not on 32-bit int! You need a bigger number container! Try the 64-bit "unsigned long long" for a few more factorials. Otherwise you have to resort to some third-party tools like Multiple Precision Arithmetic Library (http://gmplib.org), that will compute everything for you as long as you'll still have resources on your computer.