How to print the nth Catalan number
A series of positive integers are known as Catalan numbers. They can be seen in various counting problems and are used to count permutations, particular lattice path kinds, etc.
Catalan numbers have the following recursive formula:
C0 = 0 and Cn+1 = Σ Ci Cn-i for n>=0 and n=>i>=0
The first few numbers of the Catalan number series are as follows:
| n | Catalan Number |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | 5 |
| 4 | 14 |
Problem statement
Given an integer n. Find the first n Catalan numbers.
Example 1:
- Input: n=10
- Output: 1 1 2 5 14 42 132 429 1430 4862
Example 2:
- Input: n=5
- Output: 1 1 2 5 14
Solution
We can use the following recursive formula to calculate the nth Catalan number:
C0 = 0 and Cn+1 = Σ Ci Cn-i for n>=0 and n=>i>=0
The steps to implement the recursive formula are as follows:
-
Define
n. -
The base case is, if
nis less than or equal to1, it returns1. -
The recursive step is where we return the sum of the product of
i-thCatalan number andn-i-1-thCatalan number for allibetween 0 and n (0 inclusive).- Time complexity of this solutions is O(n2).
- Space complexity of this solution is
Code example
Let’s look at the code below:
class Main {static int nthCatalanNum(int n) {int sum = 0;if(n<=1) return 1;for(int i=0; i<n; i++) {sum += nthCatalanNum(i) * nthCatalanNum(n-i-1);}return sum;}public static void main(String[] args) {int n=5;System.out.println("Catalan numbers upto " + n + " are as follows:");for (int i=0; i<n; i++) {System.out.print(nthCatalanNum(i) + " ");}}}
Explanation
- Line 3: We define the
nthCatalan()funtion. - Line 4: We define
sumand initialized it to zero. - Line 5: We have the base case, when
nis less than or equal to1, then return1. - Lines 6-8: We implement the recursive step via the
forloop to find thenthCatalan number. - Line 13: We define
n. - Lines 15-17: We calculate the first
nCatalan numbers.
Free Resources