#runas solve()
#pythran export solve()
def solve():
    '''
    Pentagonal numbers are generated by the formula, P_n=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?
    '''

    MAX = 2000
    pent = [ n * (3*n - 1) / 2 for n in range(1, 2*MAX) ]
    pdic = dict.fromkeys(pent)

    def main2():
        for j in range(0, MAX):
            for k in range(j+1, 2*MAX-1):
                p_j = pent[j]
                p_k = pent[k]
                p_sum = p_j + p_k
                p_diff = p_k - p_j
                if p_sum in pdic and p_diff in pdic:
                    return p_diff

    return main2()

