関数 checkDigit は,10進9桁の整数の各桁の数字が上位の桁から順に格納された整数型の配列 originalDigit を引数として,次の手順で計算したチェックデジットを戻り値とする。プログラム中の a に入れる字句として,適切なものはどれか。ここで,配列の要素番号は1から始まる。 〔手順〕 (1) 配列 originalDigit の要素番号1~9の要素の値を合計する。 (2) 合計した値が9より大きい場合は,合計した値を 10 進の整数で表現したときの各桁の数字を合計する。この操作を,合計した値が 9 以下になるまで繰り返す。 (3) (2)で得られた値をチェックデジットとする。 〔プログラム〕 ○整数型: checkDigit(整数型の配列: originalDigit) 整数型: i, j, k j ← 0 for (i を 1 から originalDigit の要素数 まで 1 ずつ増やす) j ← j + originalDigit[i] endfor while (j が 9 より大きい) k ← j ÷ 10 の商 /* 10進9桁の数の場合, j が2桁を超えることはない */ a endwhile return j
令和4年度 ITパスポート試験 問78
This question's explanation and your answers so far.
問 78
Incorrectア
j ← j − 10 × k keeps only the ones digit (the remainder of j divided by 10) and discards the tens digit k. If j = 81 it becomes 1, which is not the intended digit sum of 9, so it is wrong.
- イ
正解 The while loop handles the process of, while the sum j is greater than 9, replacing j with the sum of its individual digits. According to the comment, j never exceeds 2 digits, so j inside the loop is a 2-digit integer. k ← quotient of j ÷ 10 is the tens digit, and the ones digit is obtained from j − 10 × k (that is, the remainder of j divided by 10). Therefore the sum of the digits is 'tens + ones' = k + (j − 10 × k), and assigning this to j is what is needed. For example, when j = 81, k = 8, the ones digit = 81 − 80 = 1, and the sum = 8 + 1 = 9, which is 9 or less, so the loop exits and correctly returns the return value 9. Hence 'イ' is appropriate.
Incorrectウ
j ← k + (j − 10) × k has a structure unrelated to the digit sum. With j = 81 and k = 8, 8 + (81 − 10) × 8 = 8 + 568 = 576 becomes huge and does not converge to 9 or less, so it is wrong.
Incorrectエ
j ← k + j merely adds the tens digit k to the original j and is not the sum of the digits. With j = 81 and k = 8 it becomes 89, which grows larger and prevents the loop from converging, so it is wrong.
- For a 2-digit integer, the tens digit can be extracted as 'the quotient of ÷ 10' and the ones digit as 'the remainder of division by 10 (= original number − 10 × quotient)'. The digit sum is the sum of these two.
- The concept of a check digit (repeatedly summing the digits until it becomes a single digit), and reading the while loop and integer division (quotient) in the pseudocode.