Project Euler : Problem 39 in Ruby

I had an easy time with this one, which makes me feel a lot better about all the ones I had problems with!

No fancy-pants recursion or math short-cuts here, just a straight forward logic problem. The only “trick” here is to realize that since a <e; b < c, we only need to check values of a and b up to 499.

I’m sure you could whittle that number down by crunching the numbers, but it’s good enough for me!

Problem 39

For which value of p 1000, is the number of solutions maximised?

counts = {}
counts.default = 0

(1..499).each do |a|
  (a..499).each do |b|
    break if a + b > 500
    c = Math.sqrt(a**2 + b**2)
    next unless c.denominator == 1
    counts[a + b + c] += 1
  end
end

sorted = counts.sort { |a, b| a[1] <=> b[1] }

puts sorted.last[0]