From 0cae02451a214cd70b36f2bf0b7a043c25aea99d Mon Sep 17 00:00:00 2001 From: Rohan Saraogi <62804340+r0sa2@users.noreply.github.com> Date: Thu, 7 Sep 2023 03:52:36 -0400 Subject: [PATCH] Added nth_sgonal_num.py (#8753) * Added nth_sgonal_num.py * Update and rename nth_sgonal_num.py to polygonal_numbers.py --------- Co-authored-by: Tianyi Zheng --- maths/polygonal_numbers.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 maths/polygonal_numbers.py diff --git a/maths/polygonal_numbers.py b/maths/polygonal_numbers.py new file mode 100644 index 000000000..7a7dc91ac --- /dev/null +++ b/maths/polygonal_numbers.py @@ -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()