The following function produces the nth number in catalan numbers. What is the exact time complexity function of this function or how can I find it myself?
int catalan(int n)
{
if (n==0 || n==1)
return 1;
int sum = 0;
for(int i=1;i<n;i++)
sum += catalan(i)*catalan(n-i);
return sum;
}
Note: I know this is the worst possible way to compute a catalan number.
To evaluate the complexity, let us focus on the number of recursive calls performed, let
C(n).A call for
nimplies exactly2(n-1)recursive calls, each of them adding their own costs,2(C(1)+C(2)+...C(n-1)).A call for
n+1implies exactly2nrecursive calls, each of them adding their own costs,2(C(1)+C(2)+...C(n-1)+C(n)).By difference,
C(n+1)-C(n) = 2+2C(n), which can be writtenC(n) = 2+3C(n-1).To solve this recurrence easily, notice that
Hence, for
n>1the exact formula isThe number of calls to
Catalan(1)(constant time), is alsoC(n), and the numbers of adds or multiplies areC(n)/2each.It is easy to reduce the complexity from
O(3^n)toO(2^n)by noting that all terms in the loop (except the middle one) are computed twice - but that still doesn't make it an acceptable implementation :)