0

Hello all mighty hackers, mathematicians and coders!

I work hard to create a recursive algorithm for the Catalan numbers equation below

C(n) =∑ C(i−1) C(n−i) (and simplification of this equation using stirling numbers or other forms is not an option..)

Here is the recursive algorithm so far:

int Cval[1024];//1024 just for example

int C( int n )
    {
    if( Cval[n] ) != ­1 ) return Cval[n];
        int ans = 0;
        if( n == 0 ) ans = 1;
        for( int i = 1; i <= n; i++ )
            ans += C( i ­- 1 ) * C( n ­- i );
                return Cval[n] = ans;
    }

int main()
{
    for( int i = 0; i < 1024; i++ ) Cval[i] = ­1;
    // call C(n) for any n up to 1023
}

Now, I'm trying to convert this to an iterative algorithm.. And I need your precious help ;) Any ideas?

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
  • Why not just use the formula C(n) = (2n choose n)/(n+1)? 2n choose n can be computed iteratively etc... Or is this homework? –  May 17 '11 at 21:25

2 Answers2

0

Create an array of C numbers, and build it up. It's actually less processing than the recursive version (which will calculate most of the numbers multiple times), and takes less space (since the array is in contiguous memory rather than being spread out through the call stack).

This also has the advantage that you can cache the results for efficient processing.

David Thornley
  • 56,304
  • 9
  • 91
  • 158
0

You are trying to implement a more general pattern known as Dynamic Programming.

The caching mechanism you use is sometimes called top-down dynamic programming, since you start calculating from the largest N first. (BTW, in your main you only need to call C() for the largest N, since the rule for Catalan numbers makes it recursively call all other values anyway).

In order to turn this algorithm into a bottom-up (iterative approach) you need to find an ordering for the arguments in such a way that C(x) only depends on elements less than x. By computing the values of C in this order you can always just use the array values directly, instead of having to rely on a memoizing function:

//initialize your base cases by hand, in 
Cval[0] = 1

//Now handle the inductive cases:
for n from 1 up to N:
    Cval[n] = 0
    for i from 1 to n:
        Cval[n] += Cval[i -1] * Cval[n -i];
    // i-1 and n-i are both less than n, so we know that
    // Cval has already been calculated for them.
hugomg
  • 68,213
  • 24
  • 160
  • 246