とんちゃんといっしょ

Cloudに関する技術とか日常とかについて書いたり書かなかったり

Problem 9

問題

Find the only Pythagorean triplet, {a, b, c}, for which a + b + c = 1000.

英語

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^(2) + b^(2) = c^(2)

For example, 3^(2) + 4^(2) = 9 + 16 = 25 = 5^(2).

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

http://projecteuler.net/index.php?section=problems&id=9

解説

どうも普通に3重ループをまわしたらしい。
らしいというのはこれを書いたときに記憶がないから。
まぁ、すぐに解けるしいいか・・・

ソースコード(Ruby)

1.upto(1000) do |d|
    sum = 0
    1.upto(1000) do |m|
        1.upto(m) do |n|
            a = d * m**2 - n**2
            b = d * 2*m*n
            c = d * m**2 + n**2
            sum = a + b + c
            sum == 1000 ? (p a*b*c;exit) : sum > 1000 ? break : next         
        end
    end
end