Project Euler: Problem 9 in Ruby

I spent way too long trying “clever” solutions that didn’t work or took twice as long as my eventual brute force solution. Screw it.

Problem #9

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.

target = 1000
min    = Math.sqrt(target).to_i
max    = target / 2

(min..max).each do |a|
  ((a + 1)..max).each do |b|
    c   = Math.sqrt(a**2 + b**2)
    sum = a + b + c
    if sum > target
      break
    elsif sum == target && (a**2 + b**2 == c**2)
      puts a * b * c
      break
    end 
  end
end

Olathe’s is pretty:

 n = 1000
a = (1..n / 2).to_a.find { |a|
  (n * (n / 2 - a) % (n - a)).zero?
}
b = n * (n / 2 - a) / (n - a)
puts "Product is #{a * b * (n - a - b)}."