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 to test the above function ; Maximum possible value of elements in both arrays .
def gcdMax ( a , b , n , N ) : NEW_LINE INDENT cnt = [ 0 ] * N NEW_LINE first = [ 0 ] * N NEW_LINE second = [ 0 ] * N NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ a [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i , N , i ) : NEW_LINE INDENT if ( cnt [ j ] ) : NEW_LINE INDENT first [ i ] = max ( first [ i ] , j ) NEW_LINE DEDENT DEDENT DEDENT cnt = [ 0 ] * N NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ b [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i , N , i ) : NEW_LINE INDENT if ( cnt [ j ] > 0 ) : NEW_LINE INDENT second [ i ] = max ( second [ i ] , j ) NEW_LINE DEDENT DEDENT DEDENT i = N - 1 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( first [ i ] > 0 and second [ i ] > 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( str ( first [ i ] ) + " ▁ " + str ( second [ i ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 1 , 4 , 2 , 8 ] NEW_LINE b = [ 5 , 2 , 12 , 8 , 3 ] NEW_LINE n = len ( a ) NEW_LINE N = 20 NEW_LINE gcdMax ( a , b , n , N ) NEW_LINE DEDENT