# Project Euler Problem 44: Pentagon numbers

Pentagonal numbers are generated by the formula, $P_n=\frac{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 :
def polygonal(s):
c = s - 2
a = b = 1
while True:
yield a
b += c
a += b

In :
def sum_diff_polygonal(s):
seen = set()
for i in polygonal(s):
for j in seen:
p = i - j
q = j
# we already know p+q=i is s-gonal
# since i must be; just need to check
# that p and p-q are as well
if p in seen and p-q in seen:
yield p, q

In :
it = sum_diff_polygonal(5)

In :
next(it)

Out:
(7042750, 1560090)
In :
def sum_diff_polygonal(s):
seen = set()
for i in polygonal(s):
for j in seen:
if i-j in seen and i-2*j in seen:
yield i-j, j

In :
it = sum_diff_polygonal(5)

In :
next(it)

Out:
(7042750, 1560090)
In :
it = sum_diff_polygonal(3)

In :
next(it)

Out:
(21, 15)
In :
next(it)

Out:
(171, 105)
In :
from itertools import islice

In :
list(islice(polygonal(3), 25))

Out:
[1,
3,
6,
10,
15,
21,
28,
36,
45,
55,
66,
78,
91,
105,
120,
136,
153,
171,
190,
210,
231,
253,
276,
300,
325]

#### TODO: Prove minimality of $| P_k - P_j |$¶

If we have $k$ such that $P_k$ is triangular and there is only one $j < k$ such that $P_j$, $P_k + P_j$ and $P_k - P_j$ is triangular then we need only minimize $k$ to minimize $| P_k - P_j |$. Otherwise, we'd need to consider $j=k-1, k-2, \cdots, 2, 1$.