ProgrammingHardTCS NQT · Accenture

Euclid's algorithm finds gcd(48, 18) by replacing the pair (a, b) with (b, a mod b) until b is 0. The loop below counts how many times the replacement happens. What is printed?

Euclid's algorithm finds gcd(48, 18) by replacing the pair (a, b) with (b, a mod b) until b is 0. The loop below counts how many times the replacement happens. What is printed?
count = 0
while b != 0
    (a, b) = (b, a mod b); count = count + 1
end while
Print count
  1. A. 6
  2. B. 5
  3. C. 3
  4. D. 0

Correct answer: C. 3

The pairs go (48,18), (18,12), (12,6), (6,0), so the loop body runs 3 times. Printing the final a gives the gcd 6 rather than the count, summing the quotients gives 5, and printing the final b gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic