Skip to content

algorithm: Hexagonal number #8003

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions maths/hexagonal_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
== Hexagonal Number ==
The nth hexagonal number hn is the number of distinct dots
in a pattern of dots consisting of the outlines of regular
hexagons with sides up to n dots, when the hexagons are
overlaid so that they share one vertex.
https://en.wikipedia.org/wiki/Hexagonal_number
"""

# Author : Akshay Dubey (https://github.com/itsAkshayDubey)


def hexagonal(number: int) -> int:
"""
:param number: nth hexagonal number to calculate
:return: the nth hexagonal number
Note: A hexagonal number is only defined for positive integers
>>> hexagonal(4)
28
>>> hexagonal(11)
231
>>> hexagonal(22)
946
>>> hexagonal(0)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> hexagonal(-1)
Traceback (most recent call last):
...
ValueError: Input must be a positive integer
>>> hexagonal(11.0)
Traceback (most recent call last):
...
TypeError: Input value of [number=11.0] must be an integer
"""
if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer")
if number < 1:
raise ValueError("Input must be a positive integer")
return number * (2 * number - 1)


if __name__ == "__main__":
import doctest

doctest.testmod()