Skip to content

Instantly share code, notes, and snippets.

@antimon2
Created September 5, 2012 03:33
Show Gist options
  • Select an option

  • Save antimon2/3629915 to your computer and use it in GitHub Desktop.

Select an option

Save antimon2/3629915 to your computer and use it in GitHub Desktop.
Project Euler 45
def sq? n
# ↓32bit整数の範囲ならとりあえずこれでOK
Math.sqrt(n).round**2 == n
end
def project_euler_45 n=143
loop do
n += 1
h = n * (2 * n - 1)
next unless sq?(8 * h + 1)
next unless sq?(24 * h + 1)
next unless Math.sqrt(24 * h + 1).to_i % 6 == 5
n3 = (Math.sqrt(8 * h + 1).to_i - 1) / 2
n5 = (Math.sqrt(24 * h + 1).to_i + 1) / 6
puts "T#{n3} = P#{n5} = H#{n} = #{h}"
return h
end
end
if $0 == __FILE__
p project_euler_45
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment