Skip to content

Commit 0486b4d

Browse files
Rishabh BafnaRishabh Bafna
authored andcommitted
Added Python file for Catalan Numbers (Cn) - A sequence of natural numbers that appear in various counting problems.
1 parent e2a78d4 commit 0486b4d

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

maths/series/catalan_numbers.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""
2+
Catalan Numbers
3+
Reference: https://en.wikipedia.org/wiki/Catalan_number
4+
5+
Catalan numbers C_n are a sequence of natural numbers that occur in
6+
various counting problems, often recursively defined.
7+
They can be computed directly using binomial coefficients:
8+
C_n = 1/(n+1) * C(2n, n)
9+
"""
10+
11+
from __future__ import annotations
12+
import math
13+
import doctest
14+
15+
16+
def catalan_numbers(count: int) -> list[int]:
17+
"""
18+
Generates the first 'count' Catalan numbers (C_0, C_1, ..., C_{count-1}).
19+
20+
:param count: The number of Catalan numbers to generate.
21+
:return: A list of integers representing the Catalan numbers.
22+
23+
Examples:
24+
>>> catalan_numbers(0)
25+
[]
26+
>>> catalan_numbers(1)
27+
[1]
28+
>>> catalan_numbers(5)
29+
[1, 1, 2, 5, 14]
30+
>>> # C_6 = 42, C_7 = 132
31+
>>> catalan_numbers(8)
32+
[1, 1, 2, 5, 14, 42, 132, 429]
33+
>>> catalan_numbers(-5)
34+
Traceback (most recent call last):
35+
...
36+
ValueError: Count must be a non-negative integer.
37+
"""
38+
if not isinstance(count, int) or count < 0:
39+
raise ValueError("Count must be a non-negative integer.")
40+
41+
if count == 0:
42+
return []
43+
44+
sequence: list[int] = []
45+
46+
for n in range(count):
47+
# Calculate C_n using the formula: C_n = (1 / (n + 1)) * (2n choose n)
48+
# Using math.comb for direct, efficient calculation of binomial coefficient
49+
# math.comb(N, K) computes N! / (K! * (N - K)!)
50+
try:
51+
binomial_coeff = math.comb(2 * n, n)
52+
c_n = binomial_coeff // (n + 1)
53+
sequence.append(c_n)
54+
except AttributeError:
55+
# Fallback for older Python versions (< 3.8) without math.comb
56+
# This uses the factorial-based formula: (2n)! / ((n+1)! n!)
57+
if n == 0:
58+
sequence.append(1)
59+
else:
60+
numerator = math.factorial(2 * n)
61+
denominator = math.factorial(n + 1) * math.factorial(n)
62+
sequence.append(numerator // denominator)
63+
64+
return sequence
65+
66+
67+
if __name__ == "__main__":
68+
doctest.testmod()
69+
70+
try:
71+
num = int(input("Enter the number of Catalan numbers to generate: "))
72+
if num < 0:
73+
print("Please enter a non-negative integer.")
74+
else:
75+
print(f"The first {num} Catalan numbers are: {catalan_numbers(num)}")
76+
except ValueError:
77+
print("Invalid input. Please enter an integer.")

0 commit comments

Comments
 (0)