IPA IP 2022 Question 79

A question IPA Japan published in 令和4年度 ITパスポート試験 公開問題 問79, translated into English. ITPEC is based on the same exams.

Same question on ITPEC: Oct 2023 Q9

When the process that is shown in the flowchart is ended, which of the following is the value of x?

StartLet x be 98Let y be 42Iterationx = y (Note)x : y≤>Let the new x bethe result ofcalculation of x - yLet the new y be theresult of calculationof y - xIterationEnd

Note: The condition of the either boundary of the iteration indicates the end condition.

Explanation

14 — the loop keeps subtracting the smaller value from the larger until x = y: Euclid's algorithm by subtraction.

The end condition x = y is checked at the top of the loop. Trace (x, y):

  • •(98, 42): x > y, so x = 98 − 42 = 56
  • •(56, 42): x > y, so x = 56 − 42 = 14
  • •(14, 42): x ≤ y, so y = 42 − 14 = 28
  • •(14, 28): x ≤ y, so y = 28 − 14 = 14
  • •(14, 14): x = y, the loop ends with x = 14

14 is the greatest common divisor of 98 and 42: 98 = 14 × 7, 42 = 14 × 3.

Answer (b)

Why not others:

  • •(a) 0 — only a subtraction after x and y became equal gives 0, and it would change y, not x; the end condition stops the loop before that
  • •(c) 28 — the value of y after the third pass, not a final value
  • •(d) 56 — x after the first pass; the loop runs on because 56 ≠ 42

Key rule: A pre-test loop checks its end condition before each pass; repeatedly subtracting the smaller number from the larger ends with both equal to the greatest common divisor.

Algorithm and Programming · AI-written, may contain errors

This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.