Program for nth Catalan Number

Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like following.

1) Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).

2) Count the number of possible Binary Search Trees with n keys

3) Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves.

The first few Catalan numbers for n = 0, 1, 2, 3, … are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, …

Recursive Solution

Following is the implementation of above recursive formula.

[pastacode lang=”python” manual=”%23%20A%20recursive%20function%20to%20find%20nth%20catalan%20number%0Adef%20catalan(n)%3A%0A%20%20%20%20%23%20Base%20Case%0A%20%20%20%20if%20n%20%3C%3D1%20%3A%0A%20%20%20%20%20%20%20%20return%201%0A%20%0A%20%20%20%20%23%20Catalan(n)%20is%20the%20sum%20of%20catalan(i)*catalan(n-i-1)%0A%20%20%20%20res%20%3D%200%0A%20%20%20%20for%20i%20in%20range(n)%3A%0A%20%20%20%20%20%20%20%20res%20%2B%3D%20catalan(i)%20*%20catalan(n-i-1)%0A%20%0A%20%20%20%20return%20res%0A%20%0A%23%20Driver%20Program%20to%20test%20above%20function%0Afor%20i%20in%20range(10)%3A%0A%20%20%20%20print%20catalan(i)%2C” message=”Python Program” highlight=”” provider=”manual”/]

Output :

1 1 2 5 14 42 132 429 1430 4862
[ad type=”banner”]