Max square size for unknown number inside rectangle

Conceptually:

  • start with 1 square
  • For each additional square, if you don’t have
    room in your grid box so far, shrink
    the existing box just enough to make
    room for an additional row or column.

pseudocode: given M x N rectangle to fill with K squares

// initial candidate grid within the rectangle
h=1
w=1
maxsquares=1
size=min(M,N) //size of the squares
while K > maxsquares
  if M/(h+1) >= N/(w+1)
    h=h+1
  else
    w=w+1
  endif
  maxsquares=h*w
  size=min(M/h,N/w)
done
print size

There are probably faster ways to jump to the answer for very large K, but I can’t think of them. If you know that M and N are integers, there may be even faster methods.

Leave a Comment