n this Divisible Sum Pairs problem you have Given an array of integers and a positive integer k, determine the number of (i,j) pairs where i < j and ar[i]+ar[j] is divisible by k.
Example
Three pairs meet the criteria: and .
Function Description
Complete the divisibleSumPairs function in the editor below.
divisibleSumPairs has the following parameter(s):
- int n: the length of array
- int ar[n]: an array of integers
- int k: the integer divisor
Returns
– int: the number of pairs
Input Format
The first line contains space-separated integers, and .
The second line contains space-separated integers, each a value of .
Constraints
Sample Input
STDIN Function
----- --------
6 3 n = 6, k = 3
1 3 2 6 1 2 ar = [1, 3, 2, 6, 1, 2]
Sample Output
5
Explanation
Here are the valid pairs when :
Breaking the Records Hacker Rank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in Python
def divisibleSumPairs(n, k, ar):
n_p = 0
for i in range(n):
for j in range(i+1,n):
if (ar[i] +ar[j]) % k == 0:
n_p= n_p +1
return n_p
Problem Solution in Java
public static int DivisibleSumPairs(List<Integer> array, Integer k) {
int result = 0;
int posicaoI = 0;
int posicaoJ = 0;
for (Integer i : array) {
posicaoJ = 0;
for (Integer j : array) {
if ((posicaoI < posicaoJ) && (((i+j)%k) == 0)) {
result++;
}
posicaoJ++;
}
posicaoI++;
}
return result;
}