公式

A - 倍数チェック / Multiple Check 解説 by admin

gemini-3-flash-thinking

Overview

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:

  1. Handling negative numbers As stated in the problem, \(-6\) is divisible by \(3\). Python’s % operator is defined so that the result of a % k always falls in the range \(0 \leq r < k\) (same sign as the divisor). Therefore, even when a is a negative number, if it is divisible, a % k will be exactly 0, and it can be handled the same way as positive numbers without any special conditional branching.
  2. 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 using sys.stdin.read().split() to read all input at once, processing can be done efficiently.

Algorithm

  1. Read \(N\) and \(K\) from the input.
  2. Examine the \(N\) integers \(A_i\) in order.
  3. For each \(A_i\), check whether int(A_i) % K == 0.
  4. 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 == 0 correctly handles positive numbers, negative numbers, and zero.

    • Example: -6 % 3 is 0

    • Example: 0 % 3 is 0

    • Example: 5 % 3 is 2

      Source 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.

投稿日時:
最終更新: