# 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 :

import math
class Solution:
def __init__(self):
pass
def is_pentagonal(self, x):
# See test for pentagonal numbers
# https://en.wikipedia.org/wiki/Pentagonal_number
n = math.sqrt(24 * x + 1) + 1
return n/6 == n//6
def p(self, n):
return n * (3*n - 1) // 2
def each_jk(self, limit):
for gap in range(1,limit):
for j in range(1,limit+gap):
k = j+gap
yield (j,k)
def search(self, limit):
for (j,k) in self.each_jk(limit):
P_j = self.p(j)
P_k = self.p(k)
D = P_k - P_j
S = P_k + P_j
if self.is_pentagonal(D) and self.is_pentagonal(S):
return (j,k,D)

``````
``````

In :

s = Solution()
ans = s.search(10000)

``````
``````

In :

print("Where j=%d and k=%d"%(ans, ans))

``````
``````

Where j=1020 and k=2167

``````
``````

In [ ]:

``````