Count pairs made up of an element divisible by the other from an array consisting of powers of 2 | Function to count the number of pairs as per the given conditions ; Initialize array set_bits as 0 ; Store the total number of required pairs ; Traverse the array arr [ ] ; Store arr [ i ] in x ; Store the position of the leftmost set bit in arr [ i ] ; Increase bit position ; Divide by 2 to shift bits in right at each step ; Count of pairs for index i till its set bit position ; Increasing count of set bit position of current elelement ; Print the answer ; Driver Code ; Function Call
function numberOfPairs ( arr , N ) { let set_bits = [ ] ; for ( let i = 0 ; i < 31 ; i ++ ) { set_bits [ i ] = 0 ; } let count = 0 ; for ( let i = 0 ; i < N ; i ++ ) { let x = arr [ i ] ; let bitpos = - 1 ; while ( x > 0 ) { bitpos ++ ; x = Math . floor ( x / 2 ) ; } for ( let j = 0 ; j <= bitpos ; j ++ ) { count += set_bits [ j ] ; } set_bits [ bitpos ] ++ ; } document . write ( count ) ; } let arr = [ 4 , 16 , 8 , 64 ] ; let N = arr . length ; numberOfPairs ( arr , N ) ;