from euler import *
from math import *
from itertools import permutations
from time import time,clock
t = time()
answer = 0


##i=10001
##done = False
##P = [n*(3*n-1)/2 for n in range(1,i)]
##S = set([n*(3*n-1)/2 for n in range(1,i*2)])
##for x in range(1,2000):
##    if done: break
##    for i in range((len(P)-x)):
##        if P[i] + P[i+x] in S:
##            if P[i+x] - P[i] in S:
##                answer = P[i+x] - P[i]
##                done = True
##
##print "answer is", answer
##print 'time', time()-t

a = set(n*(3*n-1)/2 for n in xrange(1, 5000)) 
aa = ((x,y) for x in a for y in a if x+y in a and x-y in a) 
x,y = aa.next(); print x-y

##user:sbober
##lst = [n*(3*n-1)/2 for n in xrange(1,3000)]
##s = set(lst)
## 
##for i in lst:
##    for j in lst:
##        if j > i: break
##        if (i+j) in s and abs(i-j) in s:
##            print i, j, '=', abs(i-j)

print 'time', time()-t


"""
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 is pentagonal
and D = |Pk - Pj| is minimised; what is the value of D?
"""
