Skip to content

Commit e561451

Browse files
authored
Create nth_catalan_numbers.py
1 parent 99cf2fb commit e561451

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Problem Name: Nth Catalan Numbers
2+
# Approach: Dynamic Programming
3+
4+
# -----------------------------------------------------------------------------------
5+
6+
# Problem Statement: Catalan numbers are defined as a mathematical sequence
7+
# that consists of positive integers, which can be used to
8+
# find the number of possibilities of various combinations.
9+
# Find out the catalan numbers in between the range from 0 to N.
10+
11+
12+
# -----------------------------------------------------------------------------------
13+
14+
# Constraints:
15+
# n -> Integer taken as the range of the Catalan Numbers.
16+
# catalan[] -> Array of Catalan Numbers from 0 to n.
17+
18+
# -----------------------------------------------------------------------------------
19+
20+
# A dynamic programming based function to find nth
21+
# Catalan number
22+
23+
def catalan(n):
24+
if (n == 0 or n == 1):
25+
return 1
26+
27+
# Table to store results of subproblems
28+
catalan = [0]*(n+1)
29+
30+
# Initialize first two values in table
31+
catalan[0] = 1
32+
catalan[1] = 1
33+
34+
# Fill entries in catalan[]
35+
# using recursive formula
36+
for i in range(2, n + 1):
37+
for j in range(i):
38+
catalan[i] += catalan[j] * catalan[i-j-1]
39+
40+
# Return last entry
41+
return catalan[n]
42+
43+
44+
# Driver Code
45+
print ("-- Nth Catalan Numbers using Dynamic Programming --")
46+
print ()
47+
print ("Enter the upper range : ")
48+
k = int(input())
49+
print ()
50+
print ("Printing Nth Catalan Numbers from 0 to {0}...".format(k))
51+
print ()
52+
print ("Here you go!")
53+
for i in range(k):
54+
print(catalan(i), end=" ")
55+
56+
57+
# -----------------------------------------------------------------------------------
58+
59+
# Output:
60+
# -- Nth Catalan Numbers using Dynamic Programming --
61+
62+
# Enter the upper range :
63+
# 12
64+
65+
# Printing Nth Catalan Numbers from 0 to 12...
66+
67+
# Here you go!
68+
# 1 1 2 5 14 42 132 429 1430 4862 16796 58786
69+
70+
# -----------------------------------------------------------------------------------
71+
72+
# Code Contributed by, Abhishek Sharma, 2022
73+
74+
# -----------------------------------------------------------------------------------

0 commit comments

Comments
 (0)