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
- A. 2050000000 2050000000
- B. 2147483647 2050000000
- C. -194967296 2050000000
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What is the time complexity of the following pseudocode, as a function of n? for (i = n; i > 0; 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? for (i = 1; i <= n; i = i + 1) j = 1 while (j < i) j = j 2…
- What is the time complexity of the following pseudocode, as a function of n? i = 2 while (i <= n) i = i i end while
- What is the time complexity of the following pseudocode, as a function of n? for (i = 1; i i <= n; i = i + 1) for (j = 1; j <= n; j = j 2)…
- What will be the output of the following pseudocode? (Arrays are indexed from 0; / is integer division; 'from … to …' includes both ends.)…
- What will be the output of the following pseudocode? Integer c = 0, d, k for (each x from 1 to 30) k = 0 for (each d from 1 to x) if (x…