Nth Catalan Number in Go Lang


Catalan Numbers are sequences of natural numbers that gives the number of BST (Binary Search Tree) possible with n Values. So, the Catalan number is a full binary tree with n+1 leaves.

Some applications of Catalan Numbers are counting the pairs of nested parentheses, valid mountain ranges etc.

For n = 5, C = (C(0) * C(4)) + (C(1) * C(3)) + (C(2) * C(2)) + (C(3) * C(1)) + (C(4)* C(0))

Thus, we can see that Catalan numbers are in the form of a recursive relation, i.e., for the nth term, the Catalan number Cn is,

                                             The sum of Catalan(i) * Catalan(n-i-1)

Where i ranges from 0 to (n -1).

For example, print the Catalan number for N = 5,

1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, ........

5th term in the above series is 14 thus we will print the output as ‘14’ for 5th Catalan number.

Implementation of Catalan Number

The code given below is the implementation of the nth Catalan number −

Example

 Live Demo

package main
import "fmt"
func main() {
   var n =5
   fmt.Scanf("%d", &n)
   Catalan := make([]int, n + 1)
   Catalan[0] = 1
   Catalan[1] = 1
   for i := 2; i <= n; i++ {
      for j := 0; j < i; j++ {
         Catalan[i] += (Catalan[j] * Catalan[i - j - 1])
      }
   }
   fmt.Printf("The Catalan Number (Cn) is: %d", Catalan[n - 1])
}

Output

Running the above code will generate the Catalan number for n = 5,

14

Updated on: 05-Feb-2021

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements