Skip to content

Commit 3cc035a

Browse files
r0sa2tianyizheng02
authored andcommitted
Added nth_sgonal_num.py (TheAlgorithms#8753)
* Added nth_sgonal_num.py * Update and rename nth_sgonal_num.py to polygonal_numbers.py --------- Co-authored-by: Tianyi Zheng <[email protected]>
1 parent b00c7fe commit 3cc035a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Diff for: maths/polygonal_numbers.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def polygonal_num(num: int, sides: int) -> int:
2+
"""
3+
Returns the `num`th `sides`-gonal number. It is assumed that `num` >= 0 and
4+
`sides` >= 3 (see for reference https://en.wikipedia.org/wiki/Polygonal_number).
5+
6+
>>> polygonal_num(0, 3)
7+
0
8+
>>> polygonal_num(3, 3)
9+
6
10+
>>> polygonal_num(5, 4)
11+
25
12+
>>> polygonal_num(2, 5)
13+
5
14+
>>> polygonal_num(-1, 0)
15+
Traceback (most recent call last):
16+
...
17+
ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
18+
>>> polygonal_num(0, 2)
19+
Traceback (most recent call last):
20+
...
21+
ValueError: Invalid input: num must be >= 0 and sides must be >= 3.
22+
"""
23+
if num < 0 or sides < 3:
24+
raise ValueError("Invalid input: num must be >= 0 and sides must be >= 3.")
25+
26+
return ((sides - 2) * num**2 - (sides - 4) * num) // 2
27+
28+
29+
if __name__ == "__main__":
30+
import doctest
31+
32+
doctest.testmod()

0 commit comments

Comments
 (0)