"""
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 is pentagonal and D = |P_k - P_j| is minimised.

What is the value of D?
"""

from itertools import count
from math import sqrt


def pentagonal_number(index):
    """
    >>> map(pentagonal_number, range(10))
    [0, 1, 5, 12, 22, 35, 51, 70, 92, 117]
    >>> pentagonal_number(-1)
    0
    """
    if index < 0:
        return 0

    return int(index * (3 * index - 1) / 2)


def is_pentagonal(number):
    """
    >>> all(map(is_pentagonal, [1, 5, 12, 22, 35, 51, 70, 92, 117]))
    True
    >>> any(map(is_pentagonal, [2, 3, 4, 6, 7, 8, 9, 10, 11, 23, 24]))
    False
    """
    if (sqrt(24 * number + 1)) % 6 == 5:
        return True
    return False


def main():
    """
    >>> main()
    5482660
    """
    for k in count(2):
        p_k = pentagonal_number(k)
        for j in range(k - 1, 0, -1):
            p_j = pentagonal_number(j)

            difference = p_k - p_j
            if is_pentagonal(difference):

                summe = p_k + p_j
                if is_pentagonal(summe):

                    print(difference)
                    return


if __name__ == "__main__":
    import doctest
    doctest.testmod()
