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- A. 7 6
- B. 8 6
- C. 7 5
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (operands are evaluated left to right; arrays are indexed from 0) Integer q[5], front…
- What will be the output of the following pseudocode? String in = "A+BC-D/E", out = "" Stack st = empty // prec: and / are 2, + and - are 1…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division; heap[k / 2] is the parent of…
- What will be the output of the following pseudocode? Integer table[7] = all -1, probes = 0, h for each key in {50, 700, 76, 85, 92, 73…
- What is the time complexity of the following pseudocode, as a function of n? for (i = 1; i < n; i = i 2) for (j = 0; j < i; j = j + 1)…
- What is the time complexity of the following pseudocode, as a function of n (n > 2)? while (n > 2) n = squareRoot(n) // integer square…