MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / polygonal_num

Function polygonal_num

maths/special_numbers/polygonal_numbers.py:1–26  ·  view source on GitHub ↗

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)

(num: int, sides: int)

Source from the content-addressed store, hash-verified

1def 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
29if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected