mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 23:11:09 +00:00
bcfca67faa
* [mypy] fix type annotations for problem003/sol1 and problem003/sol3 * [mypy] fix type annotations for project euler problem007/sol2 * [mypy] fix type annotations for project euler problem008/sol2 * [mypy] fix type annotations for project euler problem009/sol1 * [mypy] fix type annotations for project euler problem014/sol1 * [mypy] fix type annotations for project euler problem 025/sol2 * [mypy] fix type annotations for project euler problem026/sol1.py * [mypy] fix type annotations for project euler problem037/sol1 * [mypy] fix type annotations for project euler problem044/sol1 * [mypy] fix type annotations for project euler problem046/sol1 * [mypy] fix type annotations for project euler problem051/sol1 * [mypy] fix type annotations for project euler problem074/sol2 * [mypy] fix type annotations for project euler problem080/sol1 * [mypy] fix type annotations for project euler problem099/sol1 * [mypy] fix type annotations for project euler problem101/sol1 * [mypy] fix type annotations for project euler problem188/sol1 * [mypy] fix type annotations for project euler problem191/sol1 * [mypy] fix type annotations for project euler problem207/sol1 * [mypy] fix type annotations for project euler problem551/sol1
50 lines
1.5 KiB
Python
50 lines
1.5 KiB
Python
"""
|
||
Problem 44: https://projecteuler.net/problem=44
|
||
|
||
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten
|
||
pentagonal numbers are:
|
||
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
|
||
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
|
||
70 − 22 = 48, is not pentagonal.
|
||
|
||
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference
|
||
are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
|
||
"""
|
||
|
||
|
||
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(limit: int = 5000) -> int:
|
||
"""
|
||
Returns the minimum difference of two pentagonal numbers P1 and P2 such that
|
||
P1 + P2 is pentagonal and P2 - P1 is pentagonal.
|
||
>>> solution(5000)
|
||
5482660
|
||
"""
|
||
pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)]
|
||
for i, pentagonal_i in enumerate(pentagonal_nums):
|
||
for j in range(i, len(pentagonal_nums)):
|
||
pentagonal_j = pentagonal_nums[j]
|
||
a = pentagonal_i + pentagonal_j
|
||
b = pentagonal_j - pentagonal_i
|
||
if is_pentagonal(a) and is_pentagonal(b):
|
||
return b
|
||
|
||
return -1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print(f"{solution() = }")
|