A - 倍数チェック / Multiple Check Editorial by admin
gemini-3-flash-thinkingOverview
Given \(N\) integers \(A_1, A_2, \ldots, A_N\), the problem asks to find the count of those that are divisible by a given positive integer \(K\).
Analysis
To determine whether an integer \(a\) is divisible by \(K\), we use the modulo operator (%). Specifically, if a % K == 0 is true, then \(a\) is a multiple of \(K\).
The important points in this problem are the following two:
- Handling negative numbers
As stated in the problem, \(-6\) is divisible by \(3\). Python’s
%operator is defined so that the result ofa % kalways falls in the range \(0 \leq r < k\) (same sign as the divisor). Therefore, even whenais a negative number, if it is divisible,a % kwill be exactly0, and it can be handled the same way as positive numbers without any special conditional branching. - Time limit (fast I/O)
Since \(N\) can be as large as \(5 \times 10^5\), which is relatively large, calling Python’s standard
input()function \(N\) times may result in a Time Limit Exceeded (TLE) due to I/O overhead. By usingsys.stdin.read().split()to read all input at once, processing can be done efficiently.
Algorithm
- Read \(N\) and \(K\) from the input.
- Examine the \(N\) integers \(A_i\) in order.
- For each \(A_i\), check whether
int(A_i) % K == 0. - Count the number of times the condition is satisfied (remainder is 0), and output the final count.
Complexity
- Time complexity: \(O(N)\) Since each of the \(N\) elements is checked exactly once, the complexity is proportional to \(N\).
- Space complexity: \(O(N)\)
Since
sys.stdin.read().split()is used to hold all input in memory, the memory consumption is proportional to the input size.
Implementation Notes
Fast reading: When there is a large amount of ad-hoc input, it is efficient to convert it into a list using
sys.stdin.read().split()and then iterate over it.Modulo operation: The simple expression
a % K == 0correctly handles positive numbers, negative numbers, and zero.Example:
-6 % 3is0Example:
0 % 3is0Example:
5 % 3is2Source Code
import sys
def main():
# 入力を標準入力から一括で読み込み、空白で分割します。
# N が最大 5*10^5 と大きいため、sys.stdin.read().split() を使用して高速化します。
input_data = sys.stdin.read().split()
if not input_data:
return
# 最初の2つの要素は N と K です。
n = int(input_data[0])
k = int(input_data[1])
# 割り切れる整数の個数をカウントする変数です。
count = 0
# A_1 から A_N までの各要素についてループを回します。
# input_data[2] から input_data[2 + n - 1] までが A_i です。
for i in range(2, 2 + n):
# Python の % 演算子は、負の数に対しても a = k * q + r (0 <= r < k) となるように
# 余りを計算するため、a が k で割り切れる場合は a % k が 0 になります。
if int(input_data[i]) % k == 0:
count += 1
# 結果を出力します。
print(count)
if __name__ == "__main__":
main()
This editorial was generated by gemini-3-flash-thinking.
posted:
last update: