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
function findMaxGCD ( arr , n ) { var high = 0 ; for ( let i = 0 ; i < n ; i ++ ) high = Math . max ( high , arr [ i ] ) ; var count = Array ( high + 1 ) . fill ( 0 ) ; for ( let i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] ++ ; var counter = 0 ; for ( let i = high ; i >= 1 ; i -- ) { var j = i ; while ( j <= high ) { if ( count [ j ] > 0 ) counter += count [ j ] ; j += i ; if ( counter == 2 ) return i ; } counter = 0 ; } return 1 ; } var arr = [ 1 , 2 , 4 , 8 , 8 , 12 ] ; var n = arr . length ; document . write ( findMaxGCD ( arr , n ) ) ;