# 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 math
import progressbar


def get_pentagonal(n):

    """Returns the first n pentagonal numbers."""

    return [((i * ((3 * i) - 1)) / 2) for i in xrange(1, n + 1)]


def is_pentagonal(p):

    n = ((math.sqrt((24 * p) + 1) + 1) / 6)
    if float(n).is_integer():
        return True
    else:
        return False


def pentagonal_solve(n):

    p_list = get_pentagonal(n)
    counter = 1
    bar = progressbar.ProgressBar(max_value=n + 1)
    for i in p_list:

        counter += 1
        bar.update(counter)

        for j in p_list:

            if i < j:

                if is_pentagonal(i + j) and is_pentagonal(j - i):
                    print " "
                    return "The solution is %d." % (j - i)


print pentagonal_solve(10000)
# SOLVED
