Pairs such that one is a power multiple of other | function to count the required pairs ; sort the given array ; for each A [ i ] traverse rest array ; count Aj such that Ai * k ^ x = Aj ; increase x till Ai * k ^ x <= largest element ; driver program
function countPairs ( A , n , k ) { var ans = 0 ; A . sort ( ( a , b ) => a - b ) for ( var i = 0 ; i < n ; i ++ ) { for ( var j = i + 1 ; j < n ; j ++ ) { var x = 0 ; while ( ( A [ i ] * Math . pow ( k , x ) ) <= A [ j ] ) { if ( ( A [ i ] * Math . pow ( k , x ) ) == A [ j ] ) { ans ++ ; break ; } x ++ ; } } } return ans ; } var A = [ 3 , 8 , 9 , 12 , 18 , 4 , 24 , 2 , 6 ] ; var n = A . length ; var k = 3 ; document . write ( countPairs ( A , n , k ) ) ;