# -*- coding: utf-8 -*-
"""
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?
"""


from math import sqrt


class PE044:
  def pentagonal(self, n):
    return n * (3 * n - 1) / 2

  def isPentagonal(self, n):
    return (1 + sqrt(1 + 24 * n)) % 6 == 0

  def findPair(self, maxn=100):
    minDiff = 1000000000
    for i in range(1, maxn):
      a = self.pentagonal(i)
      for j in range(i + 1, maxn + 1):
        b = self.pentagonal(j)
        if self.isPentagonal(a + b) and self.isPentagonal(b - a):
          if b - a < minDiff:
            minDiff = b - a
    return minDiff

  @staticmethod
  def main():
    test = PE044()
    print(test.pentagonal(1))  # 1
    print(test.pentagonal(2))  # 5
    print(test.pentagonal(3))  # 12
    print(test.pentagonal(4))  # 22
    print(test.pentagonal(5))  # 35
    print(test.isPentagonal(1))  # true
    print(test.isPentagonal(4))  # false
    print(test.isPentagonal(5))  # true
    print(test.isPentagonal(12))  # true
    print(test.isPentagonal(13))  # false
    print(test.isPentagonal(144))  # false
    print(test.isPentagonal(145))  # true
    print(test.isPentagonal(146))  # false
    print(test.findPair(10000))  # 5482660


# test
PE044.main()
