Drill

ProblemsPython › patterns

The whole-number square root

mediumpatternsBinary searchMathPython

A layout routine sizes a square grid big enough to hold a number of tiles, and needs the square root as a whole number without trusting floating point.

integer_root(tiles: int) → int

Solve it in the editor →

Where you start

def integer_root(tiles: int) -> int:
    

Worked examples

CallResult
integer_root(16)4
integer_root(15)3
integer_root(1)1
integer_root(0)0

Hint

The answer lies between 0 and the input. Halve that range each step, testing whether the middle squared is still within bounds.

Reference solution in Python
def integer_root(tiles: int) -> int:
    lo, hi, best = 0, tiles, 0
    while lo <= hi:
        mid = (lo + hi) // 2
        if mid * mid <= tiles:
            best = mid
            lo = mid + 1
        else:
            hi = mid - 1
    return best

The same problem in another language

More patterns problems in Python