'''
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 are pentagonal and D = |P_k − P_j| is minimised;
what is the value of D?
'''
def pentagonalFunction(n):
    pn = (n*(3*n-1))//2
    return pn





def isSumPentagonal(i,j):
    return ((1+24*(i+j))**(0.5) % 6) == 5




'''
listOfPentagonalNumbersUpToN = []
listOfPairsOfPentagonalNumbersWhoseDifferenceAndSumArePentagonalUpToN =[]

n=5000
for i in range(1,n+1):
    listOfPentagonalNumbersUpToN.append(pentagonalFunction(i))
    for j in range(0,i-1):
        if (listOfPentagonalNumbersUpToN[i-1] - listOfPentagonalNumbersUpToN[j]) in listOfPentagonalNumbersUpToN:
            if isSumPentagonal(listOfPentagonalNumbersUpToN[i-1],listOfPentagonalNumbersUpToN[j]):
                listOfPairsOfPentagonalNumbersWhoseDifferenceAndSumArePentagonalUpToN.append((listOfPentagonalNumbersUpToN[j],listOfPentagonalNumbersUpToN[i-1]))
print(listOfPairsOfPentagonalNumbersWhoseDifferenceAndSumArePentagonalUpToN)
'''

listOfPentagonalNumbers = []
noAnswer = True
pentagonalIndex = 1

dictionaryOfPentagonalNumbers = {}


while noAnswer:
    pentagonalNumber = pentagonalFunction(pentagonalIndex)
    n = pentagonalIndex
    while pentagonalNumber > 3*n +1:
        nthPentagonalNumber = pentagonalFunction(n)
        dictionaryOfPentagonalNumbers[nthPentagonalNumber] = 1
        if isSumPentagonal(pentagonalNumber, nthPentagonalNumber) and dictionaryOfPentagonalNumbers.get(nthPentagonalNumber-pentagonalNumber,0)==1:
            listOfPentagonalNumbers.append((pentagonalNumber,nthPentagonalNumber))
            noAnswer = False
        n+=1
    pentagonalIndex +=1
    if pentagonalIndex == 10000:
        noAnswer = False
print(listOfPentagonalNumbers)

