#!/usr/bin/env ruby
# encoding: UTF-8
# Solution to Project Euler problem 85
# Author: David J. Oftedal.
# Count how many different rectangles are contained within rectangular grids
# of size x*y. Find the grid with the solution closest to 2 million.
def countSquares(gridX, gridY)
squareCount = 0
(1..gridX).each do |squareX|
(1..gridY).each do |squareY|
squareCount += (1 + gridX - squareX) * (1 + gridY - squareY)
end
end
squareCount
end
if $0 == __FILE__
bestEstimate = 0
bestX = 0
bestY = 0
currentX = 1
loop do
(1..currentX).each do |currentY|
squareCount = countSquares(currentX, currentY)
if (2000000 - squareCount).abs <= (2000000 - bestEstimate).abs
bestEstimate = squareCount
bestX = currentX
bestY = currentY
# When we get bigger counts even when generating rectangles so thin they have smaller areas, we're done.
elsif(squareCount > 2000000 && currentX*currentY <= bestX*bestY)
puts "The grid closest to 2 000 000 is " << bestX.to_s << "x" << bestY.to_s << ", with area " << (bestX*bestY).to_s << ", and " << bestEstimate.to_s << " squares."
exit(0)
end
end
currentX +=1
end
end