mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 09:10:16 +00:00
756bb268eb
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/psf/black: 22.6.0 → 22.8.0](https://github.com/psf/black/compare/22.6.0...22.8.0) - [github.com/asottile/pyupgrade: v2.37.0 → v2.38.2](https://github.com/asottile/pyupgrade/compare/v2.37.0...v2.38.2) - https://gitlab.com/pycqa/flake8 → https://github.com/PyCQA/flake8 - [github.com/PyCQA/flake8: 3.9.2 → 5.0.4](https://github.com/PyCQA/flake8/compare/3.9.2...5.0.4) - [github.com/pre-commit/mirrors-mypy: v0.961 → v0.981](https://github.com/pre-commit/mirrors-mypy/compare/v0.961...v0.981) - [github.com/codespell-project/codespell: v2.1.0 → v2.2.1](https://github.com/codespell-project/codespell/compare/v2.1.0...v2.2.1) * Fix a long line * Update sol1.py * Update sol1.py * lambda_ * Update multi_level_feedback_queue.py * Update double_ended_queue.py * Update sequential_minimum_optimization.py * Update .pre-commit-config.yaml Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
60 lines
1.5 KiB
Python
60 lines
1.5 KiB
Python
"""
|
||
Problem 45: https://projecteuler.net/problem=45
|
||
|
||
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
|
||
Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ...
|
||
Pentagonal P(n) = (n * (3 * n − 1)) / 2 1, 5, 12, 22, 35, ...
|
||
Hexagonal H(n) = n * (2 * n − 1) 1, 6, 15, 28, 45, ...
|
||
It can be verified that T(285) = P(165) = H(143) = 40755.
|
||
|
||
Find the next triangle number that is also pentagonal and hexagonal.
|
||
All triangle numbers are hexagonal numbers.
|
||
T(2n-1) = n * (2 * n - 1) = H(n)
|
||
So we shall check only for hexagonal numbers which are also pentagonal.
|
||
"""
|
||
|
||
|
||
def hexagonal_num(n: int) -> int:
|
||
"""
|
||
Returns nth hexagonal number
|
||
>>> hexagonal_num(143)
|
||
40755
|
||
>>> hexagonal_num(21)
|
||
861
|
||
>>> hexagonal_num(10)
|
||
190
|
||
"""
|
||
return n * (2 * n - 1)
|
||
|
||
|
||
def is_pentagonal(n: int) -> bool:
|
||
"""
|
||
Returns True if n is pentagonal, False otherwise.
|
||
>>> is_pentagonal(330)
|
||
True
|
||
>>> is_pentagonal(7683)
|
||
False
|
||
>>> is_pentagonal(2380)
|
||
True
|
||
"""
|
||
root = (1 + 24 * n) ** 0.5
|
||
return ((1 + root) / 6) % 1 == 0
|
||
|
||
|
||
def solution(start: int = 144) -> int:
|
||
"""
|
||
Returns the next number which is triangular, pentagonal and hexagonal.
|
||
>>> solution(144)
|
||
1533776805
|
||
"""
|
||
n = start
|
||
num = hexagonal_num(n)
|
||
while not is_pentagonal(num):
|
||
n += 1
|
||
num = hexagonal_num(n)
|
||
return num
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print(f"{solution()} = ")
|