Count of pairs of Array elements which are divisible by K when concatenated | JavaScript program to count pairs of array elements which are divisible by K when concatenated ; Function to calculate and return the count of pairs ; Compute power of 10 modulo k ; Calculate length of a [ i ] ; Increase count of remainder ; Calculate ( a [ i ] * 10 ^ lenj ) % k ; Calculate ( k - ( a [ i ] * 10 ^ lenj ) % k ) % k ; Increase answer by count ; If a pair ( a [ i ] , a [ i ] ) is counted ; Return the count of pairs ; Driver Code
let rem = new Array ( 11 ) ; for ( var i = 0 ; i < rem . length ; i ++ ) { rem [ i ] = new Array ( 2 ) ; } for ( var i = 0 ; i < rem . length ; i ++ ) { for ( var j = 0 ; j < rem . length ; j ++ ) { rem [ i ] [ j ] = 0 ; } } function countPairs ( a , n , k ) { let len = Array . from ( { length : n } , ( _ , i ) => 0 ) ; let p = Array . from ( { length : 11 } , ( _ , i ) => 0 ) ; p [ 0 ] = 1 ; for ( let i = 1 ; i <= 10 ; i ++ ) { p [ i ] = ( p [ i - 1 ] * 10 ) % k ; } for ( let i = 0 ; i < n ; i ++ ) { let x = a [ i ] ; while ( x > 0 ) { len [ i ] ++ ; x = Math . floor ( x / 10 ) ; } rem [ len [ i ] ] [ a [ i ] % k ] ++ ; } let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 1 ; j <= 10 ; j ++ ) { let r = ( a [ i ] * p [ j ] ) % k ; let xr = ( k - r ) % k ; ans += rem [ j ] [ xr ] ; if ( len [ i ] == j && ( r + a [ i ] % k ) % k == 0 ) ans -- ; } } return ans ; } let a = [ 4 , 5 , 2 ] ; let n = a . length , k = 2 ; document . write ( countPairs ( a , n , k ) ) ;