#!/usr/bin/python


#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 euler

import sys

from math import sqrt

from euler import pentagonal
from euler import is_pentagonal
from euler import gen_pentagonals

from itertools import permutations

def test():
	for p in range(10):
		print pentagonal(p), " ",
	print 

	for p in gen_pentagonals(10):
		print p , " " , 
	print

	for p in gen_pentagonals(5,10):
		print p , " " , 
	print 

	for p in range(10):
		if is_pentagonal(p):
			print p , "is pentagonal"
		else:
			print p, "is not pentagonal"

def problema44():
	j = 3
	minimum = sys.maxint
	stop=False
	while True:
		Pj = pentagonal(j)
		for k in range(1,j-1):
			#print "(", j, ",", k, ")"
			Pk = pentagonal(k)

			Sum = Pj + Pk
			Diff = abs(Pj - Pk)

			if is_pentagonal(Sum) and is_pentagonal(Diff):
				minimum=Diff
				kmin=k
				jmin=j
				print "Found new minimum:"
				print "\tP(", j, ") = ", Pj
				print "\tP(", k, ") = ", Pk
				print "\tP(", j, ")-P(",k,") = ", Diff 
				print "\tP(", j, ")+P(",k,") = ", Sum

				if (j-k)>(jmin-kmin) and Diff>minimum:
					stop=True
					#print j, "," , k, " ", jmin, " ", kmin
				#print stop
		if stop:
			break
		else:
			j+=1

#test()
problema44()
