CSES - Subarray Divisibility
Authors: Qi Wang, Brad Ma
Problem
We are asked to find the number of subarrays that are divisible by . In other words, we're supposed to find the number of subarrays with sum equal to .
Explanation
Notice that any sum of a subarray can be represented as the difference of two prefixes.
First, let represent the prefix sum of array modulo .
With our prefix sums knowledge,
Since we want to calculate the number of that equals to , must be equal to for their difference to be .
Now, we calculate , the number of prefixes with remainder equivalent to . Then the number of pairs contributed by is
The answer is just the sum of this quantity over all .
Implementation
Time Complexity:
C++
#include <iostream>#include <vector>using namespace std;/*** @author Qi Wang* (detemplifying courtesy of Kevin Sheng)*/int main() {
Java
import java.io.*;import java.util.*;public class subarrayDivisibility {public static void main(String[] args) {Kattio io = new Kattio();int n = io.nextInt();long[] M = new long[n];
Python
n = int(input())arr = map(int, input().split())residue_counts = [0] * npartial_sum = 0residue_counts[partial_sum] = 1for a in arr:partial_sum += apartial_sum = partial_sum % nresidue_counts[partial_sum] += 1# each subarray with sum divisible by n corresponds to# a pair of indices that have the same residueprint(sum(r * (r - 1) // 2 for r in residue_counts))
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!