Project Euler Problem 044

Statement

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 is pentagonal
and $D = |P_k - P_j|$ is minimised; what is the value of D?

Solution

The solution is a brute-force approach with limited number of possibilities.

from itertools import combinations
 
if __name__ == '__main__':
    pentag_list = [n * (3 * n - 1) // 2 for n in range(1, 5000)]
    setp = set(pentag_list)
    pares = [tupla for tupla in combinations(pentag_list, 2) if abs(tupla[0] - tupla[1]) in setp]
    for tupla in pares:
        suma = tupla[1] + tupla[0]
        while pentag_list[-1] < suma:
            n = len(pentag_list) + 1
            pentag_list.append(n * (3 * n -1) / 2)
        if suma in pentag_list:
            print("The result is:", abs(tupla[0] - tupla[1]))

The Python file is available for download here.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License