File tree Expand file tree Collapse file tree 2 files changed +25
-0
lines changed
Competitive Coding/Math/Catalan_Numbers Expand file tree Collapse file tree 2 files changed +25
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 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 )
You can’t perform that action at this time.
0 commit comments