forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Catalan_Number.py
58 lines (40 loc) · 1.15 KB
/
Catalan_Number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
Purpose: Calculate Nth Catalan Number
Argument : Integer
Return : Integer ( Nth Catalan Number)
Time Complexity: O(n)
Space Complexity: O(n)
Note: The Catalan Number can be to large, hence answer
is given mod of 10**9.
"""
# Catalan_Number (N) = ((2*N)!) / ((N+1)!*N!)
# Global Variables
MOD = 10**9+7
facto = [1] # Factorial Table
# To construct the factorial numbers using DP
def factorial(n):
global facto
for i in range(1, n+1):
facto += [(facto[-1]*i) % MOD]
# For Modular Inverse of num with respect to 10^9+7
def Mod_Inv(num):
return pow(num, MOD-2, MOD)
def Catalan_Number(num):
if num == 0 or num == 1:
return 1
factorial(2*num)
Numerator = facto[2*num]
Denominator = (facto[num+1]*facto[num]) % MOD
Catalan = (Numerator * Mod_Inv(Denominator)) % MOD
return Catalan
# ------------------------DRIVER CODE ------------------------
if __name__ == "__main__":
n = int(input("Enter the number: "))
print(n, "th Catalan Number = ", Catalan_Number(n), sep="")
"""
SAMPLE INPUT/OUTPUT
Enter the number: 5
5th Catalan Number = 42
Enter the number: 10
10th Catalan Number = 16796
"""