Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program for nth Catalan Number
Given an integer n, the task is to find the Catalan Number at the nth position. Catalan numbers are a sequence of natural numbers that occur in various counting problems in combinatorics and computer science.
Catalan numbers C0, C1, C2,? Cn are defined by the formula ā
$$c_{n}=\frac{1}{n+1}\binom{2n}{n} = \frac{2n!}{(n+1)!n!}$$
The first few Catalan numbers for n = 0, 1, 2, 3, ? are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ?
Syntax
unsigned long int catalan(unsigned int n);
Applications of Catalan Numbers
- Counting the number of possible binary search trees with n keys.
- Finding the number of expressions containing n pairs of parentheses which are correctly matched.
- Finding number of ways to connect points on a circle with disjoint chords.
Method 1: Using Recursion
This approach uses the recursive relation: C(n) = ? C(i) * C(n-i-1) for i from 0 to n-1 ā
#include <stdio.h>
// Recursive approach to find the catalan number
unsigned long int catalan(unsigned int n) {
// Base case
if (n <= 1)
return 1;
// catalan(n) is sum of catalan(i)*catalan(n-i-1)
unsigned long int res = 0;
for (int i = 0; i < n; i++)
res += catalan(i) * catalan(n - i - 1);
return res;
}
int main() {
int n = 6;
printf("Catalan number for n = %d is: %lu<br>", n, catalan(n));
// Display first few Catalan numbers
printf("First 8 Catalan numbers: ");
for (int i = 0; i < 8; i++) {
printf("%lu ", catalan(i));
}
printf("<br>");
return 0;
}
Catalan number for n = 6 is: 132 First 8 Catalan numbers: 1 1 2 5 14 42 132 429
Method 2: Using Dynamic Programming
This approach optimizes the recursive solution by storing previously computed values ā
#include <stdio.h>
// Dynamic Programming approach
unsigned long int catalanDP(unsigned int n) {
if (n <= 1)
return 1;
unsigned long int dp[n + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = 0;
for (int j = 0; j < i; j++) {
dp[i] += dp[j] * dp[i - 1 - j];
}
}
return dp[n];
}
int main() {
int n = 8;
printf("Catalan number for n = %d is: %lu<br>", n, catalanDP(n));
return 0;
}
Catalan number for n = 8 is: 1430
Comparison
| Method | Time Complexity | Space Complexity | Pros | Cons |
|---|---|---|---|---|
| Recursive | O(4^n) | O(n) | Simple implementation | Exponential time, repeated calculations |
| Dynamic Programming | O(n²) | O(n) | Efficient, no repeated calculations | Requires extra space for array |
Conclusion
Catalan numbers have important applications in combinatorics and computer science. While the recursive approach is intuitive, the dynamic programming solution is much more efficient for larger values of n, reducing time complexity from exponential to quadratic.
