Programming Basics (Pseudocode Tracing)

The following program subtracts the two integers a and b from each other until they are equal. What is the value of k after it runs?

integer: a ← 48, b ← 18, k ← 0
while (a ≠ b)
  if (a > b)
    a ← a − b
  else
    b ← b − a
  endif
  k ← k + 1
endwhile
  1. A3
  2. B4
  3. C6
Show answer and explanation

Answer: B. 4

This is the subtraction form of Euclid's algorithm: subtract the smaller value from the larger until the two are equal. (a, b) changes as (48, 18) → (30, 18) → (12, 18) → (12, 6) → (6, 6), four subtractions, so k = 4. The final a = b = 6 is the greatest common divisor. Euclid's algorithm with the remainder (mod) needs only three steps: 48 mod 18 = 12, 18 mod 12 = 6, 12 mod 6 = 0.

  • A. This is the number of steps of Euclid's algorithm using mod. This program uses subtraction.
  • B. Correct. Four steps from (48, 18) to (6, 6).
  • C. This is the greatest common divisor a = b = 6, not the value of k.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. The following function isLeap returns true if the year y is a leap year. and is evaluated before or. For which y does isLeap(y) return true?
  2. ÷ is division; when the result is assigned to an integer variable (including a function argument), the fractional part is discarded. When the following function pow is called as pow(2, 10), how many times is pow called, including the first call?
  3. What does the following function s return when called as s(7)?
  4. When the following procedure p is called as p(3), what sequence of values is output?
  5. What does the following function fib return when called as fib(10)?