ProgrammingHardGoldman Sachs OA · Amazon OA

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)

What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Integer n = 50, lo = 0, hi = 50, mid, ans = 0, steps = 0
while (lo <= hi)
    mid = (lo + hi) / 2
    steps = steps + 1
    if (mid * mid <= n)
        ans = mid
        lo = mid + 1
    else
        hi = mid - 1
    end if
end while
Print ans, steps
  1. A. 7 6
  2. B. 8 6
  3. C. 7 5
  4. D. 7 7

Correct answer: A. 7 6

This binary search finds the integer square root. mid runs 25, 12, 5, 8, 6, 7: after 6 probes lo = 8 > hi = 7, and ans = 7 since 7² = 49 ≤ 50 < 64. Output 7 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic