Find pair with maximum GCD in an array | function to find GCD of pair with max GCD in the array ; Calculating MAX in array ; Maintaining count array ; Variable to store the multiples of a number ; Iterating from MAX to 1 GCD is always between MAX and 1. The first GCD found will be the highest as we are decrementing the potential GCD ; Iterating from current potential GCD till it is less than MAX ; A multiple found ; Incrementing potential GCD by itself To check i , 2 i , 3 i ... . ; 2 multiples found , max GCD found ; Array in which pair with max GCD is to be found ; Size of array
< ? php function findMaxGCD ( $ arr , $ n ) { $ high = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ high = max ( $ high , $ arr [ $ i ] ) ; $ count = array_fill ( 0 , $ high + 1 , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ count [ $ arr [ $ i ] ] ++ ; $ counter = 0 ; for ( $ i = $ high ; $ i >= 1 ; $ i -- ) { $ j = $ i ; $ counter = 0 ; while ( $ j <= $ high ) { if ( $ count [ $ j ] >= 2 ) return $ j ; else if ( $ count [ $ j ] == 1 ) $ counter ++ ; $ j += $ i ; if ( $ counter == 2 ) return $ i ; } } } $ arr = array ( 1 , 2 , 4 , 8 , 8 , 12 ) ; $ n = count ( $ arr ) ; print ( findMaxGCD ( $ arr , $ n ) ) ; ? >