#44 - Pentagonal numbers
Pentagonal numbers are generated by the formula, . The first ten pentagonal numbers are:
It can be seen that . However, their difference, , is not pentagonal.
Find the pair of pentagonal numbers, and , for which their sum and difference are pentagonal and .
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,
If is an integer for a given input value, then is a valid pentagonal number. This will be the condition that we test. To minimize the difference, and need to be as close as possible to each other.
Therefore, this problem can be solved using two for loops; One to increase and the other to check all pentagonal numbers below .
# 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, .