読者です 読者をやめる 読者になる 読者になる

mu chance or much chance ?

日々の戯れ言

Project Euler 44

Project Euler

Problem44を解きました.

  • 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?

https://projecteuler.net/problem=44

問題は「五角数のペアPjとPkについて,その差と和が五角数になる場合,その差をD=|Pk - Pj|ときの最小値を求めよ.」.

def getPentagonalNum(num)
  num * (3 * num - 1) / 2
end

def isPentagonalNum(num)
  a = 1 + 24 * num
  b = Math.sqrt(a).to_i
  a == (b**2) && b % 6 == 5
end

pentagonal = []
pentagonal.push(1)

i = 2
loop do
  flag = false
  n = getPentagonalNum(i)
  pentagonal.length.times do |j|
    next unless isPentagonalNum(n - pentagonal[j]) && isPentagonalNum(n + pentagonal[j])
    p n - pentagonal[j]
    flag = true
    break
  end
  pentagonal.unshift(n)
  i += 1
  break if flag
end

五角数かどうか判断するメソッドができれば問題ないですね.