For two integer variables, if arithmetic assignments are allowed and overflow…
2018
For two integer variables, if arithmetic assignments are allowed and overflow is ignored, what is the minimum number of temporary variables needed to swap their contents?
Answer: D. 0 — ConceptA temporary variable is auxiliary storage distinct from the two variables being updated. A swap can use a reversible transformation so that both…
- A.
1
- B.
2
- C.
3
- D.
0
Attempted by 208 students.
Show answer & explanation
Correct answer: D
Concept
A temporary variable is auxiliary storage distinct from the two variables being updated. A swap can use a reversible transformation so that both original values remain recoverable during intermediate assignments; this can reduce auxiliary space.
Application
Let a = 5 and b = 3. Use only a and b:
Set a = a + b, so a = 8 and b = 3.
Set b = a - b, so b = 5 while a = 8.
Set a = a - b, so a = 3 and b = 5.
Cross-check
The final pair (a, b) = (3, 5) is the reverse of the initial pair (5, 3), and no third storage location was introduced. The no-overflow assumption keeps every arithmetic assignment valid.
Therefore, the minimum number of temporary variables is 0.