Count the number of pairs ( i , j ) such that either arr [ i ] is divisible by arr [ j ] or arr [ j ] is divisible by arr [ i ] | Function to find number of unordered pairs ; Maximum element from the array ; Array to store the frequency of each element ; Stores the number of unordered pairs ; Store the frequency of each element ; Find the number of unordered pairs ; If the number j divisible by ith element is present in the array ; If the ith element of the array has frequency more than one ; Driver code
< ? php function freqPairs ( $ arr , $ n ) { $ max = max ( $ arr ) ; $ freq = array_fill ( 0 , $ max + 1 , 0 ) ; $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ freq [ $ arr [ $ i ] ] ++ ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { for ( $ j = 2 * $ arr [ $ i ] ; $ j <= $ max ; $ j += $ arr [ $ i ] ) { if ( $ freq [ $ j ] >= 1 ) $ count += $ freq [ $ j ] ; } if ( $ freq [ $ arr [ $ i ] ] > 1 ) { $ count += $ freq [ $ arr [ $ i ] ] - 1 ; $ freq [ $ arr [ $ i ] ] -- ; } } return $ count ; } $ arr = array ( 3 , 2 , 4 , 2 , 6 ) ; $ n = count ( $ arr ) ; echo freqPairs ( $ arr , $ n ) ; ? >