ProgrammingHardTCS NQT · Accenture

For the function gcd(a, b) written by the procedure below, what is printed for gcd(252, 105)? (The procedure uses repeated remainder steps.)

For the function gcd(a, b) written by the procedure below, what is printed for gcd(252, 105)? (The procedure uses repeated remainder steps.)
function gcd(a, b)
    while b != 0
        r = a mod b; a = b; b = r
    end while
    return a
end function
Print gcd(252, 105)
  1. A. 21
  2. B. 0
  3. C. 42
  4. D. 147

Correct answer: A. 21

The remainders are 252 mod 105 = 42, 105 mod 42 = 21, and 42 mod 21 = 0, so the gcd is 21. Returning b gives 0, stopping after one remainder step gives 42, and printing the first subtraction 252 - 105 gives 147.

More Pseudocode and Code Tracing questions

Exams that ask this topic