Skip to content

Commit 24f5deb

Browse files
committed
Added 2 different implementations for Catalan Numbers
1 parent 53448ae commit 24f5deb

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
def binCoeff(n, k):#Finds the binomial coefficient
2+
if (k > n - k):#As binCoeff(n,k)=binCoeff(n,n-k)
3+
k = n - k
4+
res = 1#Initialising Result
5+
for i in range(k):
6+
res = res * (n - i)
7+
res = res / (i + 1)
8+
return res#The binomial coefficient is returned
9+
10+
def catalan(n):#Function that finds catalan numbers
11+
c = binCoeff(2*n, n)#Finding value of c by calling the binCoeff function
12+
return c/(n + 1)#This is the final catalan number
13+
14+
for i in range (5):#finds 1st 5 catalan numbers
15+
print (catalan(i))#Prints the Catalan numbers
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def catalan_numbers(n):
2+
if n <=1 :#The result will be 1, if the function takes an argument that's equal to or less than 1
3+
return 1
4+
res = 0#Result has been initialised to 0
5+
for i in range(n):
6+
res += catalan_numbers(i) * catalan_numbers(n-i-1)#The recursive function call
7+
return res
8+
9+
for i in range(5):#Implements the algo and finds the first 5 catalan numbers
10+
print catalan_numbers(i)

0 commit comments

Comments
 (0)