Here is an algorithm that finds the max value of a scaling factor F
such that all small a x b
rectangles, when scaling by F
will fit in the containing rectangle A x B
:
For every pair (p, q)
of positive integers such that
p <= n
q <= n
n = p * q - r
for some integer r >= 0
satisfying r < p
or p < q
compute f = min(A/(a*p), B/(b*q)).
- Let
F
be the maximum of all factors f
computed in 1.
The computation of all pairs (p, q)
may proceed as follows:
- [Initialize]
p := 0
- [Increment]
p := p + 1
- [End?] If
p > n
, stop
- [Next] Let
q := n + p - 1 / p
(integer division). Next pair (p, q)
.
- [Repeat] Go to 2.
Idea of the algorithm
Every pair (p, q)
represents a particular layout of the scaled rectangles with p
rectangles in an horizontal row and q
rows, the last one possibly incomplete. Here is an example for n = 13
written as 3 * 5 - 2
:

Since p
scaled rectangles of width f*a
must fit in a rectangle of width A
, we have: p*f*a <= A
or f <= A/(p*a)
. Similarly f <= B/(q*b).
Therefore the maximum scale for this configuration is min(A/(p*a), B/(q*b)).