/** * Transliterated from Python solution available here: * http://stackoverflow.com/questions/6463297/algorithm-to-fill-rectangle-with-small-squares */ private int bestSquare(float w, float h, float n) { float hi = Math.max(w, h); float lo = 0; while (Math.abs(hi - lo) > 0.0001) { float mid = (lo + hi) / 2; float midval = (float) Math.floor(w / mid) * (float) Math.floor(h / mid); if (midval >= n) { lo = mid; } else if (midval < n) { hi = mid; } } return (int) Math.min(w / Math.floor(w / lo), h / Math.floor(h / lo)); }