Drill

ProblemsC# › patterns

The whole-number square root

mediumpatternsBinary searchMathC#

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.

IntegerRoot(tiles: int) → int

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public int IntegerRoot(int tiles) {
    
}

Worked examples

CallResult
IntegerRoot(16)4
IntegerRoot(15)3
IntegerRoot(1)1
IntegerRoot(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 C#
public int IntegerRoot(int tiles) {
    long lo = 0, hi = tiles, best = 0;
    while (lo <= hi) {
        long mid = (lo + hi) / 2;
        if (mid * mid <= tiles) {
            best = mid;
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    }
    return (int) best;
}

The same problem in another language

More patterns problems in C#