Official

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

Claude 4.6 Opus (Thinking)

Overview

Given \(N\) integers, the problem asks to count how many of them are divisible by a positive integer \(K\).

Analysis

  • Whether an integer \(a\) is divisible by \(K\) can be determined by checking if the remainder when \(a\) is divided by \(K\) is \(0\). That is, if \(a \mod K = 0\), then \(a\) is divisible by \(K\).
  • Note that \(A_i\) may include negative numbers or \(0\), but in Python the modulo operator % works correctly for negative numbers, and a % K == 0 correctly determines divisibility.
    • Examples: \(-6 \% 3 = 0\) (divisible), \(0 \% 5 = 0\) (divisible)
  • Since this problem can be solved by checking each element exactly once, no special algorithm is needed. Simply iterating through all elements and counting those that satisfy the condition is fast enough under the constraint \(N \leq 5 \times 10^5\).

Concrete Example

For \(N = 5, K = 3, A = [3, -6, 7, 0, 9]\):

\(A_i\) \(A_i \% 3\) Divisible?
\(3\) \(0\)
\(-6\) \(0\)
\(7\) \(1\)
\(0\) \(0\)
\(9\) \(0\)

The answer is 4.

Algorithm

  1. Read \(N\) and \(K\) from input.
  2. Read the \(N\) integers \(A_1, A_2, \ldots, A_N\).
  3. For each \(A_i\), check whether \(A_i \% K == 0\).
  4. Count and output the number of elements satisfying the condition.

In the code, the generator expression sum(1 for a in A if a % K == 0) is used, which adds \(1\) for each element satisfying the condition and computes the total.

Complexity

  • Time complexity: \(O(N)\) — Only one modulo operation is performed for each element.
  • Space complexity: \(O(N)\) — Required to store the input list \(A\).

Implementation Notes

  • Python’s modulo operation and negative numbers: In Python, the result of \(a \% K\) (where \(K > 0\)) is always in the range \(0\) to \(K - 1\). Therefore, even when \(a\) is negative, a % K == 0 correctly determines divisibility. In C++ and Java, the handling of modulo for negative numbers differs, so caution is needed when solving in other languages.

  • Using generator expressions: sum(1 for a in A if a % K == 0) counts without creating a new list, making it a memory-efficient approach.

    Source Code

N, K = map(int, input().split())
A = list(map(int, input().split()))
print(sum(1 for a in A if a % K == 0))

This editorial was generated by claude4.6opus-thinking.

posted:
last update: