# -*- coding: utf-8 -*-

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

以下の条件を満たす五角数のペアを探す
・その和も五角数となる
・その差が最も最小となる
'''


from math import sqrt


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


def is_pentagonal(num):
    return (sqrt(24 * num + 1) + 1) % 6.0 == 0


def find_pair(Pk, pentagonal_numbers):
    for Pj in pentagonal_numbers[::-1]:
        _sum = Pk + Pj
        _diff = Pk - Pj
        if is_pentagonal(_sum) and _diff in pentagonal_numbers:
            return _diff
    return None


if __name__ == '__main__':

    k = 1
    D = None
    pentagonal_numbers = []

    while D is None:
        Pk = pentagonal_number(k)
        pentagonal_numbers.append(Pk)
        D = find_pair(Pk, pentagonal_numbers)
        if D is not None:
            print('k=%d, j=%d' % (k, pentagonal_numbers.index(Pk - D) + 1))
            print('D is %d' % D)
        k += 1
