Count pairs in array whose sum is divisible by K

Given an array A[] and positive integer K , the task is to count total number of pairs in the array whose sum is divisible by K .
Note : This question is generalised version of this

Examples:

Input : A = {2, 2, 1, 7, 5, 3}, K = 4 Output : 5 Explaination : There are five pairs possible whose sum is divisible by ‘4’ i.e., (2, 2), (1, 7), (7, 5), (1, 3) and (5, 3) Input : A = {5, 9, 36, 74, 52, 31, 42}, K = 3 Output : 7


i try to write the code but the output is wronge…


function pair_sum(arr::Vector{T}, k::Integer) where T<:Integer
 
 sum = 0 
 for i in length(arr)
    for j = 1:length(arr)
    merge_both = arr[i] + arr[j]
      if mod(merge_both, k) == 0
        sum +=1
      end
    end
 end
return sum 
 end
arr = [5,9,36,74,52,31,42]
println("Total pairs   " , pair_sum(arr, 3))

The for loop in it is not exactly correct. It should be:

for i in 1:length(arr)
   for j in (i+1):length(arr)
   ...
   end
end

This question might also be better in the Usage (First Steps) rather than Development category.

1 Like