Batu Lab NotesPractical developer guides

Use integer square root for a capacity estimate

By Batu ยท English technical notes

Also published in our Blogger archive.

Use integer square root for a capacity estimate

When a square layout needs one unit of capacity per cell, a budget of n cells can support at most floor(sqrt(n)) rows and columns. math.isqrt(n) calculates that integer square root without first converting the integer to a float. The returned value is the greatest integer whose square is no larger than n.

The example starts with a capacity of 50 cells. math.isqrt(50) returns 7, so a 7-by-7 square uses 49 cells and fits. The next side length, 8, would use 64 cells and does not fit. Those two assertions test the defining boundary relationship rather than merely checking a preselected result. The output states both the side length and the unused cell count.

math.isqrt requires a nonnegative integer. A negative capacity is rejected with ValueError in the helper, while non-integer inputs are not converted implicitly. Use a different policy if fractions represent valid capacity in the application. This calculation estimates only the largest square under the supplied cell budget; it does not account for headers, spacing, rectangular layouts, or allocation overhead.

math.isqrt was added in Python 3.8. Its exact floor semantics and input requirements are specified in the official math.isqrt documentation.

AI assistance disclosure: This article was drafted with AI assistance and is intended as a small standard-library example.

import math


def square_side_that_fits(cell_capacity):
    if cell_capacity < 0:
        raise ValueError("cell capacity must be nonnegative")
    return math.isqrt(cell_capacity)


capacity = 50
side = square_side_that_fits(capacity)
used = side * side

assert used <= capacity
assert (side + 1) ** 2 > capacity

print(f"side={side}, unused={capacity - used}")
side=7, unused=1