Skip to content
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

Added nth_sgonal_num.py #8753

Merged
merged 2 commits into from
Sep 7, 2023
Merged
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
32 changes: 32 additions & 0 deletions maths/polygonal_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
def polygonal_num(num: int, sides: int) -> int:
"""
Returns the `num`th `sides`-gonal number. It is assumed that `num` >= 0 and
`sides` >= 3 (see for reference https://en.wikipedia.org/wiki/Polygonal_number).

>>> polygonal_num(0, 3)
0
>>> polygonal_num(3, 3)
6
>>> polygonal_num(5, 4)
25
>>> polygonal_num(2, 5)
5
>>> polygonal_num(-1, 0)
Traceback (most recent call last):
...
ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
>>> polygonal_num(0, 2)
Traceback (most recent call last):
...
ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
"""
if num < 0 or sides < 3:
raise ValueError("Invalid input: num must be >= 0 and sides must be >= 3.")

return ((sides - 2) * num**2 - (sides - 4) * num) // 2


if __name__ == "__main__":
import doctest

doctest.testmod()