# EulerProblem044

# Pentagon numbers (Euler Problem 44)¶

Back to overview.

https://projecteuler.net/problem=44

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?

In [3]:

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

    assert(pentagonal(1) == 1)
    assert(pentagonal(4) == 22)

In [31]:

    n = 10000
    p = [pentagonal(n) for n in range(1, n)]
    p_set = set(p)

Okay, I was honestly just going for plain brute force here and the first solution that came up was the solution to the problem... Not really happy with that.

In [33]:

    for i in range(1, n):
        for j in range(i + 1, n):
            if p[i - 1] + p[j - 1] in p_set and p[j - 1] - p[i - 1] in p_set:
                d = pentagonal(j) - pentagonal(i)
                s = d
                print("i = {}, j = {}, d = {}.".format(i, j, d))

    i = 1020, j = 2167, d = 5482660.

In [35]:

    print(s)
    assert(s == 5482660)

    5482660

In [ ]: