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 = 1000, 0, 1000, 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. 31 10
  2. B. 31 9
  3. C. 31 11
  4. D. 32 9

Correct answer: B. 31 9

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

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

Exams that ask this topic