Skip to content

Commit 5654c62

Browse files
algorithm: Hexagonal number (#8003)
* feat: Add hexagonal number * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 6a86fe4 commit 5654c62

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

maths/hexagonal_number.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
== Hexagonal Number ==
3+
The nth hexagonal number hn is the number of distinct dots
4+
in a pattern of dots consisting of the outlines of regular
5+
hexagons with sides up to n dots, when the hexagons are
6+
overlaid so that they share one vertex.
7+
8+
https://en.wikipedia.org/wiki/Hexagonal_number
9+
"""
10+
11+
# Author : Akshay Dubey (https://github.com/itsAkshayDubey)
12+
13+
14+
def hexagonal(number: int) -> int:
15+
"""
16+
:param number: nth hexagonal number to calculate
17+
:return: the nth hexagonal number
18+
Note: A hexagonal number is only defined for positive integers
19+
>>> hexagonal(4)
20+
28
21+
>>> hexagonal(11)
22+
231
23+
>>> hexagonal(22)
24+
946
25+
>>> hexagonal(0)
26+
Traceback (most recent call last):
27+
...
28+
ValueError: Input must be a positive integer
29+
>>> hexagonal(-1)
30+
Traceback (most recent call last):
31+
...
32+
ValueError: Input must be a positive integer
33+
>>> hexagonal(11.0)
34+
Traceback (most recent call last):
35+
...
36+
TypeError: Input value of [number=11.0] must be an integer
37+
"""
38+
if not isinstance(number, int):
39+
raise TypeError(f"Input value of [number={number}] must be an integer")
40+
if number < 1:
41+
raise ValueError("Input must be a positive integer")
42+
return number * (2 * number - 1)
43+
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
48+
doctest.testmod()

0 commit comments

Comments
 (0)