Skip to content

[New Algorithm] - Triangular Numbers #10663

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 4 commits into from
Oct 23, 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
43 changes: 43 additions & 0 deletions maths/special_numbers/triangular_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""
A triangular number or triangle number counts objects arranged in an
equilateral triangle. This module provides a function to generate n'th
triangular number.

For more information about triangular numbers, refer to:
https://en.wikipedia.org/wiki/Triangular_number
"""


def triangular_number(position: int) -> int:
"""
Generate the triangular number at the specified position.

Args:
position (int): The position of the triangular number to generate.

Returns:
int: The triangular number at the specified position.

Raises:
ValueError: If `position` is negative.

Examples:
>>> triangular_number(1)
1
>>> triangular_number(3)
6
>>> triangular_number(-1)
Traceback (most recent call last):
...
ValueError: param `position` must be non-negative
"""
if position < 0:
raise ValueError("param `position` must be non-negative")

return position * (position + 1) // 2


if __name__ == "__main__":
import doctest

doctest.testmod()