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

mu chance or much chance ?

日々の戯れ言

Project Euler 45

Project Euler

Problem45を解きました.

  • Triangular, pentagonal, and hexagonal

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.

Find the next triangle number that is also pentagonal and hexagonal.

https://projecteuler.net/problem=45

問題は「三番目に小さい,三角数かつ五角数かつ六角数な自然数を求めよ.」.

def getHexagonalNum(num)
  num * (2 * num - 1)
end

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

def isTriangleNum(num)
  a = 1 + 8 * num
  b = Math.sqrt(a).to_i
  a == (b**2) && b.odd?
end

count = 0
i = 0
loop do
  i += 1
  n = getHexagonalNum(i)
  if isPentagonalNum(n) && isTriangleNum(n)
    p n
    count += 1
  end
  break if count == 3
end

Problem44で作成したメソッドを利用して,
三角数かどうかを判断するメソッドを作成できれば問題ないですね.