#!/usr/bin/python3
# -*- coding: utf-8 -*-


'''
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?
'''

TOP=10**4


def pentagonal(n):
    return n * (3*n - 1) // 2


def pentagonals(c):
    r = [0,1]
    n = 1
    v = 1
    while n < c:
       v = v + 3*n + 1
       r.append(v)
       n = n + 1
    return r

def main():
    
    plist = pentagonals(TOP)
    pset = set(plist)
    
    dmin = 10**12
    result_j = 0
    
    for diff in range(1,TOP):
#      print(diff)
      for j in range(1,TOP-diff):
        pj = plist[j]
        pk = plist[j+diff]
        dminus = pk - pj
        dplus = pk + pj
        if (dminus in pset) and (dplus in pset):
#          print (pj,pk,d)
          if dminus < dmin:
            result = [j, diff, dminus, dplus, pj,pk]
            dmin = dminus
            print (result)
    
def xmain():
    print(sorted(pentagonals(1000)))
    
if  __name__ =='__main__':main()
