JOEZACK.COM Code Musings and Such

2Jul/110

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]
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.