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, \dots\]
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\)?
The goal is to find \(j,k,d,s\) such that \(P_k - P_j = P_d\) and \(P_k + P_j = P_s\), and \(P_d\) is minimized. To guarantee this last condition, my program iterates over increasing values of \(d\).
The expression \(P_d = P_k - P_j\) evaluates to \(\frac 12 d(3d-1) = \frac 12 (3k^2 - k) - \frac 12 (3j^2 - j)\). This simplifies to \(d(3d-1) = (k-j)(3k+3j-1)\). As such, I iterate over all factors \(a\) of \(2P_d\) using a SymPy function, set \(b = \dfrac{2P_d}{a}\), and solve the system of equations \(a = k-j, b = 3k+3j-1\) for \(k\) and \(j\). This inner loop breaks when \(b < 3a\).
The system of equations has the solution \(k = \dfrac{3a + b + 1}6\) and \(j = \dfrac{-3a + b + 1}6\), which is a pair of integers if \(b \equiv 2 \mod 3\) and \(a\) and \(\dfrac{b+1}3\) have the same parity. From there, it's a matter of checking whether \(P_k + P_j\) is a pentagonal number. If \(P_k + P_j = \dfrac{s(3s-1)}2\) for \(s > 0\), then by the quadratic formula, \(s = \dfrac{1 + \sqrt{1 + 24(P_k + P_j)}}6\). If this is an integer, we're done.
from itertools import count
from sympy import divisors
from math import isqrt
def p44():
for d in count(1):
Pd2 = d * (3*d - 1)
for a in divisors(Pd2):
b = Pd2 // a
if b < 3 * a:
break
if b % 3 == 2:
c = (b + 1) // 3
if a % 2 == c % 2:
k = (a + c) // 2
j = (c - a) // 2
Pk2 = k * (3*k - 1)
Pj2 = j * (3*j - 1)
Ps2 = Pk2 + Pj2
if isqrt(1+12*Ps2)**2 == 1+12*Ps2 and (1 + isqrt(1 + 12*Ps2)) % 6 == 0:
return Pd2 // 2