#44 - Pentagonal numbers

Pentagonal numbers are generated by the formula, Pn=12n(3n1)P_n=\frac{1}{2}n(3n-1). The first ten pentagonal numbers are: 1,5,12,22,35,51,70,92,117,145,1,5,12,22,35,51,70,92,117,145,\dots

It can be seen that P4+P7=22+70=92=P8P_4+P_7=22+70=92=P_8. However, their difference, 7022=4870-22=48, is not pentagonal.

Find the pair of pentagonal numbers, PjP_j and PkP_k, for which their sum and difference are pentagonal and D=PjPkD=\lvert P_j - P_k\rvert.


Just like #42 - Coded triangle numbers, we need to test if a given number is a pentagonal number. Solving the equation by the quadratic formula, we get, n=1+24Pn+16n=\frac{1+\sqrt{24P_n+1}}{6}

If nn is an integer for a given input value, then PnP_n is a valid pentagonal number. This will be the condition that we test. To minimize the difference, PjP_j and PkP_k need to be as close as possible to each other.

Therefore, this problem can be solved using two for loops; One to increase PkP_k and the other to check all pentagonal numbers below PkP_k.

# file: "problem044.py"
def isPentagonal(x):
    n = ((24 * x + 1) ** 0.5 + 1) / 6
    return int(n) == n

notFound = True
k = 2
while notFound:
    Pk = k * (3 * k - 1) // 2
    for j in range(k - 1, 0, -1):
        Pj = j * (3 * j - 1) // 2
        if isPentagonal(Pk + Pj) and isPentagonal(Pk - Pj):
            print(Pk - Pj)
            notFound = False
            break
    k += 1

The output is,

5482660
2.5649144140300306 seconds.

Thus, D=5482660D=\mathbf{5482660}.

0