Back to Project Euler

Previous Problem Next Problem

Problem 44: Pentagon Numbers

Pentagonal numbers are generated by the formula, Pn=n(3n1)/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, 7022=48, is not pentagonal.

Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D=|PkPj| is minimised; what is the value of D?

Solution

The goal is to find j,k,d,s such that PkPj=Pd and Pk+Pj=Ps, and Pd is minimized. To guarantee this last condition, my program iterates over increasing values of d.

The expression Pd=PkPj evaluates to 12d(3d1)=12(3k2k)12(3j2j). This simplifies to d(3d1)=(kj)(3k+3j1). As such, I iterate over all factors a of 2Pd using a SymPy function, set b=2Pda, and solve the system of equations a=kj,b=3k+3j1 for k and j. This inner loop breaks when b<3a.

The system of equations has the solution k=3a+b+16 and j=3a+b+16, which is a pair of integers if b2mod3 and a and b+13 have the same parity. From there, it's a matter of checking whether Pk+Pj is a pentagonal number. If Pk+Pj=s(3s1)2 for s>0, then by the quadratic formula, s=1+1+24(Pk+Pj)6. If this is an integer, we're done.

Python Code

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

Previous Problem Next Problem

Back to Project Euler