Maths Help - Calculate for a Grid

The elegant way is via the rectangle packing. The brute force you described would work. Ugly, indeed.