# Count pairs in array whose sum is divisible by K

**URL:** <https://discourse.julialang.org/t/count-pairs-in-array-whose-sum-is-divisible-by-k/28266>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [September 1, 2019, 4:51pm UTC](https://discourse.julialang.org/t/count-pairs-in-array-whose-sum-is-divisible-by-k/28266 "2019-09-01T16:51:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fuad\_Sami](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/fuad_sami/32/16900_2.png) [@Fuad\_Sami](https://discourse.julialang.org/u/Fuad_Sami)\
**Post date:** [September 1, 2019, 4:51pm UTC](https://discourse.julialang.org/t/count-pairs-in-array-whose-sum-is-divisible-by-k/28266/1 "2019-09-01T16:51:37Z")

</div>

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](https://www.geeksforgeeks.org/count-pairs-array-whose-sum-divisible-4/)

**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…

* * *

```julia
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))

```

---

<div class="post-metadata">

**Author:** ![Syx\_Pek](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/syx_pek/32/6364_2.png) [@Syx\_Pek](https://discourse.julialang.org/u/Syx_Pek)\
**Post date:** [September 1, 2019, 5:01pm UTC](https://discourse.julialang.org/t/count-pairs-in-array-whose-sum-is-divisible-by-k/28266/2 "2019-09-01T17:01:41Z")

</div>

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

```julia
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.
