Problem 207
Subarrays Divisible by K
Medium · 20 pts · Array, Hash Table, Prefix Sum
Problem
You are given an array of N integers and a number K. Count the non-empty blocks of consecutive elements whose sum is divisible by K (a sum of 0 counts as divisible). Blocks at different positions count separately. Two prefix sums with the same remainder mod K enclose a block whose sum is divisible by K. So count how many prefix sums fall into each remainder class, including the empty prefix 0, and add up count × (count - 1) / 2 over the classes. Careful: with negative numbers, normalise the remainder into the range 0 to K - 1.
Input
First line: integers N and K. Second line: N space-separated integers.
Output
Print the number of such subarrays.
Constraints
1 <= N <= 30000; -10000 <= A[i] <= 10000; 2 <= K <= 10000
Example input
6 5 4 5 0 -2 -3 1
Example output
7
Explanation
In 4 5 0 -2 -3 1 with K = 5, the qualifying blocks are 4 5 0 -2 -3 1, 5, 5 0, 5 0 -2 -3, 0, 0 -2 -3 and -2 -3. Their sums are 5, 5, 5, 0, 0, -5 and -5, all divisible by 5, which is 7 blocks.