![]() |
VOOZH | about |
Given two arrays of n integers with values of the array being small (values never exceed a small number say 100). Find the pair(x, y) which has maximum gcd. x and y cannot be of the same array. If multiple pairs have the same gcd, then consider the pair which has the maximum sum.
Examples:
Input : a[] = {3, 1, 4, 2, 8}
b[] = {5, 2, 12, 8, 3}
Output : 8 8
Explanation: The maximum gcd is 8 which is
of pair(8, 8).
Input: a[] = {2, 3, 5}
b[] = {7, 11, 13}
Output: 5 13
Explanation: Every pair has a gcd of 1.
The maximum sum pair with GCD 1 is (5, 13)
A naive approach will be to iterate for every pair in both the arrays and find out the maximum gcd possible. Below is the code for naive approach.
Pair with greatest GCD: (24, 72) with GCD: 24
Time complexity : O(M*N) where M , N are the sizes of the array
Auxiliary space : O(1)
An efficient (only when elements are small) is to apply the sieve property and for that, we need to pre-calculate the following things.
Below is the implementation of the above approach :
Maximum GCD pair with maximum sum is 8 8
Time complexity : O(N Log N + N), as we are using nested loops where outer loop traverses N times and inner loop traverses logN times (as N + (N/2) + (N/3) + ..... + 1 = N log N) and we are using extra Loop to traverse N times.
Auxiliary Space : O(N), as we are using extra space for cnt array.