Find pair with maximum GCD in an array | function to find GCD of pair with max GCD in the array ; Computing highest element ; Array to store the count of divisors i . e . Potential GCDs ; Iterating over every element ; Calculating all the divisors ; Divisor found ; Incrementing count for divisor ; Element / divisor is also a divisor Checking if both divisors are not same ; Checking the highest potential GCD ; If this divisor can divide at least 2 numbers , it is a GCD of at least 1 pair ; Array in which pair with max GCD is to be found ; Size of array
function findMaxGCD ( arr , n ) { var high = 0 ; for ( var i = 0 ; i < n ; i ++ ) high = Math . max ( high , arr [ i ] ) ; var divisors = Array . from ( { length : high + 1 } , ( _ , i ) => 0 ) ; for ( var i = 0 ; i < n ; i ++ ) { for ( var j = 1 ; j <= Math . sqrt ( arr [ i ] ) ; j ++ ) { if ( arr [ i ] % j == 0 ) { divisors [ j ] ++ ; if ( j != arr [ i ] / j ) divisors [ arr [ i ] / j ] ++ ; } } } for ( var i = high ; i >= 1 ; i -- ) if ( divisors [ i ] > 1 ) return i ; return 1 ; } var arr = [ 1 , 2 , 4 , 8 , 8 , 12 ] ; var n = arr . length ; document . write ( findMaxGCD ( arr , n ) ) ;