ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// 32-bit signed integers; overflow wraps around (two's complement); / truncates toward zero
Integer lo = 2000000000, hi = 2100000000
Integer mid1 = (lo + hi) / 2
Integer mid2 = lo + (hi - lo) / 2
Print mid1, mid2
  1. A. 2050000000 2050000000
  2. B. 2147483647 2050000000
  3. C. -194967296 2050000000
  4. D. -97483648 2050000000

Correct answer: D. -97483648 2050000000

lo + hi = 4 100 000 000 exceeds 2 147 483 647, so it wraps to 4 100 000 000 − 4 294 967 296 = −194 967 296, and halving gives −97 483 648. The safe form lo + (hi − lo)/2 never overflows: 2 000 000 000 + 50 000 000 = 2 050 000 000. This is the classic binary-search midpoint bug. 2050000000 for both ignores the overflow; −194967296 forgets the division; 2147483647 assumes the sum saturates instead of wrapping.

More Pseudocode and Code Tracing questions

Exams that ask this topic