Skip to content

Commit 4514a7c

Browse files
Tauseef-Hilalsedatguzelsemme
authored andcommitted
[New Algorithm] - Triangular Numbers (TheAlgorithms#10663)
* Add New Algorithm: Triangular Numbers * Calculate nth triangular number instead of generating a list * Handle 0th position and update function name and docstring
1 parent 8e4504c commit 4514a7c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Diff for: maths/special_numbers/triangular_numbers.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
A triangular number or triangle number counts objects arranged in an
3+
equilateral triangle. This module provides a function to generate n'th
4+
triangular number.
5+
6+
For more information about triangular numbers, refer to:
7+
https://en.wikipedia.org/wiki/Triangular_number
8+
"""
9+
10+
11+
def triangular_number(position: int) -> int:
12+
"""
13+
Generate the triangular number at the specified position.
14+
15+
Args:
16+
position (int): The position of the triangular number to generate.
17+
18+
Returns:
19+
int: The triangular number at the specified position.
20+
21+
Raises:
22+
ValueError: If `position` is negative.
23+
24+
Examples:
25+
>>> triangular_number(1)
26+
1
27+
>>> triangular_number(3)
28+
6
29+
>>> triangular_number(-1)
30+
Traceback (most recent call last):
31+
...
32+
ValueError: param `position` must be non-negative
33+
"""
34+
if position < 0:
35+
raise ValueError("param `position` must be non-negative")
36+
37+
return position * (position + 1) // 2
38+
39+
40+
if __name__ == "__main__":
41+
import doctest
42+
43+
doctest.testmod()

0 commit comments

Comments
 (0)