VOOZH about

URL: https://www.geeksforgeeks.org/dsa/pair-maximum-gcd-two-arrays/

⇱ Pair with maximum GCD from two arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Pair with maximum GCD from two arrays

Last Updated : 18 Sep, 2023

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.


Output
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. 
 

  1. A cnt array to mark the presence of array elements.
  2. We check for all the numbers from 1 to N and for each multiple, we check that if the number exists then the max of the pre-existing number or the present existing multiple is stored.
  3. Step 1 and 2 is repeated for the other array also.
  4. At the end we check for the maximum multiple which is common in both first and second array to get the maximum GCD, and in the position of is stored the element, in first the element of an array is stored, and in second the element of b array is stored, so we print the pair.

Below is the implementation of the above approach :


Output
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.


 

Comment
Article Tags: