Hi, why does the two functions factorial and factorial2 only return the right factorial if the input is 12 or less ?

``````#include "iostream"

using namespace std;

int factorial(int n){
if (n==0){
return 1;
}
else{
return n*factorial(n-1);
}
}

int factorial2 ( int x ) {
int p = 1;
for ( int i = 2; i <= x; i++ ) {
p = p * i;
}
return p;
}

int main(void){

int b = 0;
do{
cout << "Enter a number: " << endl;
cin >> b;
cout << b << "! = " << factorial(b) << " or " << factorial2(b) << endl;
}while(b>0);

}``````
2
Contributors
1
2
Views
6 Years
Discussion Span
Last Post by VernonDozier

When a recursive function works for n, but not n + 1, chances are it's one of these 3...

1. Mathematically there's a whole in the logic. Probably not the case here.
2. You've run out of stack space. Probably not the case here.
3. You've exceeded the bounds of a type.

I'm guessing 3 here. An int can hold up to a little over 2 billion. If 13! is more than that, it can't contain it, so you'll need a type that can, say uint64_t.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.