"""
EP - 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?
"""
import math

def isPentagon(n):
    # A number x is pentagon if (sqrt(24x + 1) + 1) // 6 exists
    value = (math.sqrt(24 * n + 1) + 1) % 6
    if value == 0:
        return True
    else:
        return False

def compute():
    i = 1
    while True:
        i += 1
        for j in range(1,i):
            pk = i*(3*i-1) // 2
            pj = j*(3*j-1) // 2
            if isPentagon(pk+pj) and isPentagon(pk-pj):
                return abs(pk-pj)

print(compute())

