mu chance or much chance ?

日々の戯れ言

Project Euler 44

  • 問題

Problem 44:Pentagon numbers
Pentagonal numbers are generated by the formula, Pn=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 P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.

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

  • 解答例
import math

def isPentagonalNum(n):
    x = (math.sqrt(24 * n + 1) + 1) / 6.0
    return x.is_integer()

ans = 0
isfound = False
k = 2
 
while not isfound:
    pk = k * (3 * k - 1) // 2
    j = k - 1
    while j > 0:
        pj = j * (3 * j - 1) // 2
        if isPentagonalNum(pk - pj) and isPentagonalNum(pk + pj):
            ans = pk - pj
            isfound = True
            break
        j -= 1
    k += 1

print(ans)