TryBugHunt
rustInfinite loopHard

Whole-number square root never returns

BugFind the bug and fix the code

What it should do

int_sqrt(n) returns the largest whole number whose square is at most n, using binary search. Example: int_sqrt(10) → 3

What happens instead

int_sqrt(10) never returns. The run is stopped by the time limit. int_sqrt(0) works.

fn int_sqrt(n: i32) -> i32 {
    let mut lo = 0;
    let mut hi = n;
    while lo < hi {
        let mid = (lo + hi) / 2;
        if mid * mid <= n {
            lo = mid;
        } else {
            hi = mid - 1;
        }
    }
    lo
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

A hard Rust debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: (lo + hi) / 2 rounds down. When only two candidates are left, say lo = 3 and hi = 4, mid is 3. 3 * 3 <= 10, so lo = mid sets lo to 3 again. Nothing changes, and the loop repeats forever.

The fix: When the update is lo = mid, round mid up instead: (lo + hi + 1) / 2. Then mid is always greater than lo and the range shrinks every time.

Remember: in a binary search, every branch must make the range smaller. If one branch is lo = mid, use the upper middle. If it is hi = mid, use the lower middle. Trace the case with two values left.

The pattern behind it: infinite loops.

More infinite loops to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/59d2e7ee-f728-467b-a8e4-112f20171408" title="Debugging challenge: Whole-number square root never returns" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/59d2e7ee-f728-467b-a8e4-112f20171408">TryBugHunt</a></p>