Recursive factorial function not working properly
c++, recursion
Solution
The factorial of 21 is `51090942171709440000`. A signed long long on your computer can hold has a maximum of `2^63-1 = 9223372036854775807`.
2432902008176640000 20 factorial
9223372036854775807 2^63-1 (the maximum for a long long on your computer)
51090942171709440000 21 factorial
When a number is larger than the maximum then behavior is undefined. What happens on most computers is that it wraps around to the most negative number.
Problem
Why this recursive function can only calculate up to (20!) ? When I input 21 it shows unexpected result. ``` #include <iostream> using namespace std; long long int factorial( long long int number ) { if( number <= 1 ) return 1; return number * factorial( number - 1 ); ``` } ``` int main() { long long int number; while( cin >> number ) cout << factorial( number ) << endl; // factorial( 20 ) = 2432902008176640000 // factorial( 21 ) = -4249290049419214848 ???? return 0; } ```