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/C++ Program for nth Catalan Number?
Catalan numbers are a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects. The nth Catalan number can be calculated using the recursive formula or dynamic programming approaches.
Syntax
C(n) = (2n)! / ((n+1)! * n!) C(n) = C(0)*C(n-1) + C(1)*C(n-2) + ... + C(n-1)*C(0)
Mathematical Properties
Catalan numbers have several interpretations −
- Cn is the number of Dyck words of length 2n (strings with n X's and n Y's where no prefix has more Y's than X's)
- Cn counts valid parentheses combinations with n pairs
- Cn represents ways to parenthesize n+1 factors completely
- Cn is the number of full binary trees with n+1 leaves
Method 1: Recursive Approach
The simplest approach uses the recursive formula where each Catalan number is the sum of products of previous Catalan numbers −
#include <stdio.h>
long int catalan(int n) {
if (n <= 1) {
return 1;
}
long int result = 0;
for (int i = 0; i < n; i++) {
result += catalan(i) * catalan(n - i - 1);
}
return result;
}
int main() {
printf("First 6 Catalan numbers: ");
for (int i = 0; i < 6; i++) {
printf("%ld ", catalan(i));
}
printf("\n");
return 0;
}
First 6 Catalan numbers: 1 1 2 5 14 42
Method 2: Dynamic Programming
For better efficiency, we can use dynamic programming to avoid recalculating the same values −
#include <stdio.h>
long int catalanDP(int n) {
if (n <= 1) return 1;
long int catalan[n + 1];
catalan[0] = catalan[1] = 1;
for (int i = 2; i <= n; i++) {
catalan[i] = 0;
for (int j = 0; j < i; j++) {
catalan[i] += catalan[j] * catalan[i - j - 1];
}
}
return catalan[n];
}
int main() {
int n = 10;
printf("Catalan numbers from 0 to %d:\n", n);
for (int i = 0; i <= n; i++) {
printf("C(%d) = %ld\n", i, catalanDP(i));
}
return 0;
}
Catalan numbers from 0 to 10: C(0) = 1 C(1) = 1 C(2) = 2 C(3) = 5 C(4) = 14 C(5) = 42 C(6) = 132 C(7) = 429 C(8) = 1430 C(9) = 4862 C(10) = 16796
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(4^n) | O(n) | Small values, conceptual understanding |
| Dynamic Programming | O(n²) | O(n) | Larger values, efficiency |
Conclusion
Catalan numbers can be computed using recursive formulas or dynamic programming. The DP approach is more efficient for larger values, avoiding redundant calculations with O(n²) complexity instead of exponential time.
