Skip to content

Commit

Permalink
Merge pull request #130 from Bilwasiva/patch-2
Browse files Browse the repository at this point in the history
Created catalan_numbers.cpp
  • Loading branch information
Ayushsinhahaha authored Oct 28, 2022
2 parents 8800e6d + 2f4d9f1 commit 8df73aa
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions catalan_numbers.cpp
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;
}

0 comments on commit 8df73aa

Please sign in to comment.