Pair with maximum GCD from two arrays | Find the maximum GCD pair with maximum sum ; array to keep a count of existing elements ; first [ i ] and second [ i ] are going to store maximum multiples of i in a [ ] and b [ ] respectively . ; traverse through the first array to mark the elements in cnt ; Find maximum multiple of every number in first array ; Find maximum multiple of every number in second array . We re - initialise cnt [ ] and traverse through the second array to mark the elements in cnt ; if the multiple is present in the second array then store the max of number or the pre - existing element ; traverse for every elements and checks the maximum N that is present in both the arrays ; driver program ; Maximum possible value of elements in both arrays .
function gcdMax ( a , b , n , N ) { let cnt = Array . from ( { length : N } , ( _ , i ) => 0 ) ; let first = Array . from ( { length : N } , ( _ , i ) => 0 ) ; let second = Array . from ( { length : N } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < n ; ++ i ) cnt [ a [ i ] ] = 1 ; for ( let i = 1 ; i < N ; ++ i ) for ( let j = i ; j < N ; j += i ) if ( cnt [ j ] > 0 ) first [ i ] = Math . max ( first [ i ] , j ) ; cnt = Array . from ( { length : N } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < n ; ++ i ) cnt [ b [ i ] ] = 1 ; for ( let i = 1 ; i < N ; ++ i ) for ( let j = i ; j < N ; j += i ) if ( cnt [ j ] > 0 ) second [ i ] = Math . max ( second [ i ] , j ) ; let x ; for ( x = N - 1 ; x >= 0 ; x -- ) if ( first [ x ] > 0 && second [ x ] > 0 ) break ; document . write ( first [ x ] + " " + second [ x ] ) ; } let a = [ 3 , 1 , 4 , 2 , 8 ] ; let b = [ 5 , 2 , 12 , 8 , 3 ] ; let n = a . length ; let N = 20 ; gcdMax ( a , b , n , N ) ;