C++ :
int divisibleSumPairs(int n, int k, vector<int> ar) {
int noOfPairs = 0, sum = 0;
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
sum = ar[i] + ar[j];
if(sum % k == 0){
noOfPairs++;
}
}
}
return noOfPairs;
}
Explanation:
This is about adding two numbers at ar[i] and ar[j], such that the sum is divisible by k. n is the ar.size(), which is actually no need to be provided, but since it is, let’s use it.
For the inner for loop, j is (i + 1), so that double summing doesn’t happen (eg. ar[2] + ar[4] and ar[4] and ar[2], since i < j is a requirement for the question. The rest is relatively straightforward.