Data Structures & AlgorithmsVery hardCodeforces Div2 C · GATE CS

A binary search finds the largest x with xx <= 50 using the bounds 0 and 50.

A binary search finds the largest x with x*x <= 50 using the bounds 0 and 50.
lo, hi = 0, 50
while lo < hi:
    mid = (lo + hi + 1) // 2
    if mid * mid <= 50: lo = mid
    else: hi = mid - 1
print(lo)
What is printed?
  1. A. 8
  2. B. 25
  3. C. 7
  4. D. 6

Correct answer: C. 7

Rounding mid up, (lo + hi + 1) // 2, is needed when the update is lo = mid: with rounding down, lo = mid can stall forever when lo and hi are adjacent. The variant here keeps the same bounds but moves the boundary by one, so it reports the first failing value (8) instead of 7.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic