TITLE: Algorithm to get the maximum size of n squares that fit into a rectangle with a given width and height
QUESTION [31 upvotes]: I am looking for an algorithm that can return the number of size of n squares that fit into a a rectangle of a given width and height, maximizing the use of space (thus, leaving the least amount of leftover space for squares that do not fit). Neither the rectangle nor the squares can be rotated.
For example, let's say I have a rectangle that is 5 inches by 7 inches, and I need it to fit 35 squares. The algorithm needs to tell me that the 35 squares fit if they are 1 inch wide/tall (as they could be laid out inside the rectangle in a 5 x 7 grid). Another example is if I need to divide a rectangle 35 inches by 1 inch into 35 squares. It should still tell me that the squares will fit if they are 1-inch wide/tall (as they could be laid out in the rectangle in a 35 x 1 grid).
The tricky part is that sometimes there may be leftover space, as the squares cannot be divided into partial squares. Let's say for either of the two examples above I need to lay out 34 squares and not 35 (in which case the answers would still be 1 inch), or maybe 33, or 7 squares. Or, perhaps the rectangle width and height aren't whole numbers. With the number of squares being a variable I need an algorithm that can tell me the size of the squares for a given rectangle width and height.
Thanks for your help!

REPLY [9 votes]: chubakueno's solution doesn't always work. Take for example $x=10$, $y=2$ and $n=8$. His algorithm returns 1 whereas the biggest square size is obtained by fitting one single line of eight squares, and is therefore $10/8=1.25$.
Below is an algorithm that works, written in Javascript. It also has the advantage of computing the minimum number of rows and columns, on top of the square size. Inputs are x, y and n.
// Compute number of rows and columns, and cell size
var ratio = x / y;
var ncols_float = Math.sqrt(n * ratio);
var nrows_float = n / ncols_float;

// Find best option filling the whole height
var nrows1 = Math.ceil(nrows_float);
var ncols1 = Math.ceil(n / nrows1);
while (nrows1 * ratio < ncols1) {
    nrows1++;
    ncols1 = Math.ceil(n / nrows1);
}
var cell_size1 = y / nrows1;

// Find best option filling the whole width
var ncols2 = Math.ceil(ncols_float);
var nrows2 = Math.ceil(n / ncols2);
while (ncols2 < nrows2 * ratio) {
    ncols2++;
    nrows2 = Math.ceil(n / ncols2);
}
var cell_size2 = x / ncols2;

// Find the best values
var nrows, ncols, cell_size;
if (cell_size1 < cell_size2) {
    nrows = nrows2;
    ncols = ncols2;
    cell_size = cell_size2;
} else {
    nrows = nrows1;
    ncols = ncols1;
    cell_size = cell_size1;
}