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);
	
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.