Skip to content

Add Catalan number to maths #6845

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@
* [Binomial Coefficient](maths/binomial_coefficient.py)
* [Binomial Distribution](maths/binomial_distribution.py)
* [Bisection](maths/bisection.py)
* [Catalan Number](maths/catalan_number.py)
* [Ceil](maths/ceil.py)
* [Check Polygon](maths/check_polygon.py)
* [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py)
Expand Down Expand Up @@ -632,8 +633,9 @@

## Physics
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py)
* [Lorenz Transformation Four Vector](physics/lorenz_transformation_four_vector.py)
* [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py)
* [N Body Simulation](physics/n_body_simulation.py)
* [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py)
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)

## Project Euler
Expand Down
51 changes: 51 additions & 0 deletions maths/catalan_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""

Calculate the nth Catalan number

Source:
https://en.wikipedia.org/wiki/Catalan_number

"""


def catalan(number: int) -> int:
"""
:param number: nth catalan number to calculate
:return: the nth catalan number
Note: A catalan number is only defined for positive integers

>>> catalan(5)
14
>>> catalan(0)
Traceback (most recent call last):
...
ValueError: Input value of [number=0] must be > 0
>>> catalan(-1)
Traceback (most recent call last):
...
ValueError: Input value of [number=-1] must be > 0
>>> catalan(5.0)
Traceback (most recent call last):
...
TypeError: Input value of [number=5.0] must be an integer
"""

if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer")

if number < 1:
raise ValueError(f"Input value of [number={number}] must be > 0")

current_number = 1

for i in range(1, number):
current_number *= 4 * i - 2
current_number //= i + 1

return current_number


if __name__ == "__main__":
import doctest

doctest.testmod()