Here's the piece of code:
int catalan(int n)
{
if (n<0){
return 0;
}
if (n<=1){
return 1;
}
int total = 0;
for(int i=0;i<n;i++)
{
total += catalan(i)*catalan(n-i-1);
}
return total;
}
int main(int argc, char* argv[])
{
int res;
try{
res = catalan(stoi(argv[1]));
}catch (const std::out_of_range& e) {
cout << "Input number out of range.";
return 0;
}
cout<<res<<endl;
return 0;
}
When I do catalan(20), it should equal to 6,564,120,420, however since the maximum value a signed int can store is 2,147,483,647, the stored result as a signed int will result in an integer overflow and a weird answer '-2025814172'.
I handled the input out of range problem using the try catch, but I don't know how to handle the return value from the recursion function when it is too large. I wanted to print error message for it but not sure how to do that.