Chapter 2 Computing Catalan Numbers

Definition 2.1
The Catalan numbers c0,c1,c2, are defined recursively as follows: c0=1c1=1()cn=k=0n1ckcn1k=c0cn1+c1cn2++cn1c0( for n2). For example, c2=c0c1+c1c0=1×1+1×1=2,c3=c0c2+c1c1+c2c0=1×2+1×1+2×1=5,

We write a recursive function CatalanRecursive(n) which returns the n-th Catalan number.

def CatalanRecursive(n):
    if n == 0:
        return 1
    if n == 1:
        return 1
    else:
        Cn = 0
        for i in range(0, n):
            Cn += CatalanRecursive(i) * CatalanRecursive(n - 1 - i)

    return Cn

We write a non-recursive function CatalanNotRecursive(n) which returns the n-th Catalan number.

def CatalanNonRecursive(n):
    if n == 0:
        return 1
    if n == 1:
        return 1
    C = [0] * (n + 1)
    C[0] = 1
    C[1] = 1
    for i in range(2, n + 1):
        C[i] = 0
        for j in range(0, i):
            C[i] += C[j] * C[i - j - 1]

    return C[n]

We can compare the execution times of these two method of computing the Catalan numbers, where we have the graph of following.

knitr::include_graphics('static/pic1.png')

From the graph that we plot, we can see that the recursive function is much slower than the non recursive one. From n=10 the recursive function takes much more time than the non recursive one and increases exponentially. This is due to in the computation of cn, the recursive function calls itself too much time with repeated computation. However, in the non recursive function we use list to store the values of cn and we don’t need to compute them again.