Chapter 2 Computing Catalan Numbers
Definition 2.1
The Catalan numbers are defined recursively as follows:
For example,
We write a recursive function CatalanRecursive(n)
which returns the -th Catalan number.
def CatalanRecursive(n):
if n == 0:
return 1
if n == 1:
return 1
else:
= 0
Cn for i in range(0, n):
+= CatalanRecursive(i) * CatalanRecursive(n - 1 - i)
Cn
return Cn
We write a non-recursive function CatalanNotRecursive(n)
which returns the -th Catalan number.
def CatalanNonRecursive(n):
if n == 0:
return 1
if n == 1:
return 1
= [0] * (n + 1)
C 0] = 1
C[1] = 1
C[for i in range(2, n + 1):
= 0
C[i] for j in range(0, i):
+= C[j] * C[i - j - 1]
C[i]
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.
::include_graphics('static/pic1.png') knitr
From the graph that we plot, we can see that the recursive function is much slower than the non recursive one. From the recursive function takes much more time than the non recursive one and increases exponentially. This is due to in the computation of , 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 and we don’t need to compute them again.