-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
C++ program to find the nth Catalan Number
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
// C++ program to find the nth Catalan Number | ||
#include <iostream> | ||
using namespace std; | ||
|
||
// Returns value of Binomial Coefficient C(n, k) | ||
unsigned long int binomialCoeff(unsigned int n, | ||
unsigned int k) | ||
{ | ||
unsigned long int res = 1; | ||
|
||
if (k > n - k) | ||
k = n - k; | ||
|
||
for (int i = 0; i < k; ++i) { | ||
res *= (n - i); | ||
res /= (i + 1); | ||
} | ||
|
||
return res; | ||
} | ||
|
||
// A Binomial coefficient based function to find nth catalan | ||
// number in O(n) time | ||
unsigned long int catalan(unsigned int n) | ||
{ | ||
unsigned long int c = binomialCoeff(2 * n, n); | ||
|
||
return c / (n + 1); | ||
} | ||
|
||
// Driver code | ||
int main() | ||
{ | ||
for (int i = 0; i < 10; i++) | ||
cout << catalan(i) << " "; | ||
return 0; | ||
} |