ProgrammingHardTCS NQT · Accenture

Two positive integers are a = 252 and b = 105. The procedure below finds their gcd by repeated subtraction. How many times does the loop body run (the number of subtraction steps) before the algorithm stops?

Two positive integers are a = 252 and b = 105. The procedure below finds their gcd by repeated subtraction. How many times does the loop body run (the number of subtraction steps) before the algorithm stops?
steps = 0
while a != b
    if a > b then a = a - b else b = b - a
    steps = steps + 1
end while
Print steps
  1. A. 5
  2. B. 0
  3. C. 3
  4. D. 10

Correct answer: A. 5

The subtractions run 252-105, 147-105, 105-42, 63-42, 42-21 and stop at (21, 21), which is 5 steps. Printing the count before any step gives 0, doubling each step gives 10, and the remainder version takes 3 steps.

More Pseudocode and Code Tracing questions

Exams that ask this topic