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- A. 5
- B. 0
- C. 3
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Let N = 360. The procedure below counts the divisors of N by testing every i from 1 to N. What is printed? count = 0 for i = 1 to N if N…
- A number's digit sum is computed by the procedure below for N = 98765. What is printed? s = 0; m = N while m > 0 s = s + (m mod 10) m = m…
- The procedure below uses the sieve of Eratosthenes on the range 2 to 50, marking composites starting from ii. The inner marking statement…
- Compute 3^13 mod 7 with the binary method below (a = 3, e = 13, m = 7). What is printed? result = 1; base = a mod m; e = 13 while e > 0 if…
- Let phi(n) be the number of integers i with 1 <= i <= n that share no common factor with n except 1. The procedure below computes phi(36)…
- Starting from n = 27, the Collatz step is applied: if n is even, n becomes n/2, otherwise n becomes 3n + 1. The procedure below counts the…