Count number of pairs in array having sum divisible by K | SET 2 | C # Program to count pairs whose sum divisible by ' K ' ; Program to count pairs whose sum divisible by ' K ' ; Create a frequency array to count occurrences of all remainders when divided by K ; To store count of pairs . ; Traverse the array , compute the remainder and add k - remainder value hash count to ans ; Count number of ( A [ i ] , ( K - rem ) % K ) pairs ; Increment count of remainder in hash map ; Driver code
using System ; class GFG { static int countKdivPairs ( int [ ] A , int n , int K ) { int [ ] freq = new int [ K ] ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int rem = A [ i ] % K ; ans += freq [ ( K - rem ) % K ] ; freq [ rem ] ++ ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] A = { 2 , 2 , 1 , 7 , 5 , 3 } ; int n = A . Length ; int K = 4 ; Console . WriteLine ( countKdivPairs ( A , n , K ) ) ; } }