Count number of pairs in array having sum divisible by K | SET 2 | 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
function countKdivPairs ( A , n , K ) { var freq = Array ( K ) . fill ( 0 ) ; var ans = 0 ; for ( var i = 0 ; i < n ; i ++ ) { var rem = A [ i ] % K ; ans += freq [ ( K - rem ) % K ] ; freq [ rem ] ++ ; } return ans ; } var A = [ 2 , 2 , 1 , 7 , 5 , 3 ] ; var n = A . length ; var K = 4 ; document . write ( countKdivPairs ( A , n , K ) ) ;