• + 3 comments

    First of all, we need to notice that (A + B) % K = ([A/K] * K + A % K + [B/K] * K + B % K) % K = (A % K + B % K) % K (i.e. remainder of the sum equals to the remainder of the sum of the remainders). What it gives us is that in order to find B knowing A where (A + B) % K it's enough just to look at A % K and B % K.

    Then, consider we are at some item A[j] right now and we need to calculate how many pairs this A[j] makes with all the previous items A[i], i < j. That is actually a number of items A[i], i < j where A[i] % K complements A[j] % K. By "complements" here I mean that (A[i] % K + A[j] % K) % K == 0. That actually means that they are either both == 0 or their sum == K. (K - A[j] % K) % K effectively calculates this complement.

    Wrapping it up, we divide all the items in A into buckets by A[i] % K value. This gives us the ability at each step to see how many pairs we have involving some item A[i]. Iterating the array once and calculating only pairs on the left helps us not to count one pair two times while still covering all the combinations.

    Hope this helps.