I have the job of verifying and if it is possible to calculate the catalan number by means of the tail recursion, I could do the calculation with the stack recursion using the definition, but I could not do it by means of the tail recursion
int catalan(int n){
if(n==0){
return 1;
}
else{
return 2*(2*n-1)*Catalan(n-1)/(n+1);
}
}
Specify the multiplier and the divisor as parameters to the function,
and a wrapper function
which supplies initial values for the extra parameters. Basically, we postpone the calculation done on the return value, by supplying the intermediate result as extra parameters, so that the deepest iteration can do it.
We have to supply the multiplier and the divisor as separate values, because the result is only guaranteed to be integer for the final iteration.
The "Optional TODO" part is not particular to Catalan numbers per se, but is generally advisable when dealing with factorials and multiplication and divison. The binary approach for greatest common divisor is easy to implement and sufficiently fast, and often helps keep the intermediate values within the range of the type used.
A simple way to find out if
c = a*boverflows, is to check ifc/a == b(assuming positivea,a >= 1).