Data Structures & AlgorithmsHardGATE CS · DSA

Integer square root by binary search (largest m with m·m ≤ n). What is printed (root, iterations)?

Integer square root by binary search (largest m with m·m ≤ n). What is printed (root, iterations)?
n, lo, hi, it = 777, 0, 777, 0
while lo < hi:
    it += 1
    mid = (lo + hi + 1) // 2
    if mid * mid <= n: lo = mid
    else: hi = mid - 1
print(lo, it)
  1. A. 27 9
  2. B. 27 11
  3. C. 26 9
  4. D. 29 9

Correct answer: A. 27 9

Rounding mid UP is essential with lo = mid, otherwise the loop can stall when hi = lo + 1. Output: 27 9.

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

Exams that ask this topic