mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
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>
This commit is contained in:
parent
6a86fe4867
commit
5654c6242e
48
maths/hexagonal_number.py
Normal file
48
maths/hexagonal_number.py
Normal file
@ -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()
|
Loading…
Reference in New Issue
Block a user