Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

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 = 200, 0, 200, 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. 14 8
  2. B. 14 9
  3. C. 14 10
  4. D. 14 7

Correct answer: A. 14 8

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

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

Exams that ask this topic