I simply used a hash to store the frequencies of remainders when divided by 7:
int count7Divisibiles(int arr[], int n)
{
// Create a frequency array to count
// occurrences of all remainders when
// divided by 7
int freq[7] = {0, 0, 0, 0, 0, 0, 0};
// Count occurrences of all remainders
for (int i = 0; i < n; i++)
++freq[arr[i] % 7];
// If both pairs are divisible by '7'
int ans = freq[0] * (freq[0] - 1) / 2;
// If one of them is equal
// to 1 modulo 7 and the
// other is equal to 3
// modulo 7
ans += freq[1] * freq[6];
// for 2%7 and 5%7
ans += freq[2] * freq[5];
//for 3%7 and 4%7
ans += freq[3] * freq[4];
return ans;
}
- If both are divisible by 7, then use
n*(n-1)/2
- Else do
count(a%7)*count((7-a)%7)
21
solved C++ Program Bug [closed]