Pentagonal numbers are generated by the formula, \$P_n=\frac{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 \$P_4 + P_7 = 22 + 70 = 92 = P_8\$. However, their difference, \$70 − 22 = 48\$, is not pentagonal.
Find the pair of pentagonal numbers, \$P_j\$ and \$P_k\$, for which their sum and difference are pentagonal and \$D = |P_k − P_j|\$ is minimised; what is the value of D?
Awaiting feedback.
from time import time
def generate_pentagons(n):
"""generates next n pentagons"""
pentagons = (num * (3 * num - 1) // 2 for num in range(1, n))
for i in range(n - 1):
yield next(pentagons)
def get_pentagons(n):
"""Assumes n is a range > 0.
generates pentagons that obey to the + - rules."""
pentagons = set(generate_pentagons(n))
for pentagon1 in pentagons:
for pentagon2 in pentagons:
if pentagon1 + pentagon2 in pentagons and abs(pentagon1 - pentagon2) in pentagons:
return pentagon1, pentagon2
if __name__ == '__main__':
start_time = time()
pent1, pent2 = get_pentagons(10000)
print(abs(pent1 - pent2))
print(f'Time: {time() - start_time} seconds.')