# Pair with maximum GCD from two arrays

• Difficulty Level : Medium
• Last Updated : 08 Jun, 2022

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

## C++

 `// CPP program to find maximum GCD pair``// from two arrays``#include ``using` `namespace` `std;` `// Find the maximum GCD pair with maximum``// sum``void` `gcdMax(``int` `a[], ``int` `b[], ``int` `n, ``int` `N)``{``    ``// array to keep a count of existing elements``    ``int` `cnt[N] = { 0 };` `    ``// first[i] and second[i] are going to store``    ``// maximum multiples of i in a[] and b[]``    ``// respectively.``    ``int` `first[N] = { 0 }, second[N] = { 0 };` `    ``// traverse through the first array to``    ``// mark the elements in cnt``    ``for` `(``int` `i = 0; i < n; ++i)``        ``cnt[a[i]] = 1;` `    ``// Find maximum multiple of every number``    ``// in first array``    ``for` `(``int` `i = 1; i < N; ++i)``        ``for` `(``int` `j = i; j < N; j += i)``            ``if` `(cnt[j])``                ``first[i] = max(first[i], j);` `    ``// 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``    ``memset``(cnt, 0, ``sizeof``(cnt));``    ``for` `(``int` `i = 0; i < n; ++i)``        ``cnt[b[i]] = ``true``;``    ``for` `(``int` `i = 1; i < N; ++i)``        ``for` `(``int` `j = i; j < N; j += i)` `            ``// if the multiple is present in the``            ``// second array then store the  max``            ``// of number or the  pre-existing``            ``// element``            ``if` `(cnt[j])``                ``second[i] = max(second[i], j);` `    ``// traverse for every elements and checks``    ``// the maximum N that is present in both``    ``// the arrays``    ``int` `i;``    ``for` `(i = N - 1; i >= 0; i--)``        ``if` `(first[i] && second[i])``            ``break``;` `    ``cout << ``"Maximum GCD pair with maximum "``            ``"sum is "` `<< first[i] << ``" "``         ``<< second[i] << endl;``}` `// driver program to test the above function``int` `main()``{``    ``int` `a[] = { 3, 1, 4, 2, 8 };``    ``int` `b[] = { 5, 2, 12, 8, 3 };``    ``int` `n = ``sizeof``(a) / ``sizeof``(a[0]);` `    ``// Maximum possible value of elements``    ``// in both arrays.``    ``int` `N = 20;` `    ``gcdMax(a, b, n, N);``    ``return` `0;``}`

## Java

 `// Java program to find maximum``// GCD pair from two arrays``class` `GFG``{``    ` `// Find the maximum GCD``// pair with maximum sum``static` `void` `gcdMax(``int``[] a, ``int``[] b,``                   ``int` `n, ``int` `N)``{``    ``// array to keep a count``    ``// of existing elements``    ``int``[] cnt = ``new` `int``[N];` `    ``// first[i] and second[i]``    ``// are going to store``    ``// maximum multiples of``    ``// i in a[] and b[]``    ``// respectively.``    ``int``[] first = ``new` `int``[N];``    ``int``[] second = ``new` `int``[N];` `    ``// traverse through the``    ``// first array to mark``    ``// the elements in cnt``    ``for` `(``int` `i = ``0``; i < n; ++i)``        ``cnt[a[i]] = ``1``;` `    ``// Find maximum multiple``    ``// of every number in``    ``// first array``    ``for` `(``int` `i = ``1``; i < N; ++i)``        ``for` `(``int` `j = i; j < N; j += i)``            ``if` `(cnt[j] > ``0``)``                ``first[i] = Math.max(first[i], j);` `    ``// 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``    ``cnt = ``new` `int``[N];``    ``for` `(``int` `i = ``0``; i < n; ++i)``        ``cnt[b[i]] = ``1``;``    ``for` `(``int` `i = ``1``; i < N; ++i)``        ``for` `(``int` `j = i; j < N; j += i)` `            ``// if the multiple is present``            ``// in the second array then``            ``// store the max of number or``            ``// the pre-existing element``            ``if` `(cnt[j] > ``0``)``                ``second[i] = Math.max(second[i], j);` `    ``// traverse for every``    ``// elements and checks``    ``// the maximum N that``    ``// is present in both``    ``// the arrays``    ``int` `x;``    ``for` `(x = N - ``1``; x >= ``0``; x--)``        ``if` `(first[x] > ``0` `&&``            ``second[x] > ``0``)``            ``break``;` `    ``System.out.println(first[x] + ``" "` `+``                            ``second[x]);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int``[] a = { ``3``, ``1``, ``4``, ``2``, ``8` `};``    ``int``[] b = { ``5``, ``2``, ``12``, ``8``, ``3` `};``    ``int` `n = a.length;` `    ``// Maximum possible``    ``// value of elements``    ``// in both arrays.``    ``int` `N = ``20``;` `    ``gcdMax(a, b, n, N);``}``}` `// This code is contributed``// by mits`

## Python3

 `# Python 3 program to find maximum GCD pair``# from two arrays` `# Find the maximum GCD pair with maximum``# sum``def` `gcdMax(a, b, n, N):` `    ``# array to keep a count of existing elements``    ``cnt ``=` `[``0``]``*``N` `    ``# first[i] and second[i] are going to store``    ``# maximum multiples of i in a[] and b[]``    ``# respectively.``    ``first ``=` `[``0``]``*``N``    ``second ``=` `[``0``]``*``N` `    ``# traverse through the first array to``    ``# mark the elements in cnt``    ``for` `i ``in` `range``(n):``        ``cnt[a[i]] ``=` `1` `    ``# Find maximum multiple of every number``    ``# in first array``    ``for` `i ``in` `range``(``1``,N):``        ``for` `j ``in` `range``(i,N,i):``            ``if` `(cnt[j]):``                ``first[i] ``=` `max``(first[i], j)` `    ``# 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``    ``cnt ``=` `[``0``]``*``N``    ``for` `i ``in` `range``(n):``        ``cnt[b[i]] ``=` `1``    ``for` `i ``in` `range``(``1``,N):``        ``for` `j ``in` `range``(i,N,i):` `            ``# if the multiple is present in the``            ``# second array then store the max``            ``# of number or the pre-existing``            ``# element``            ``if` `(cnt[j]>``0``):``                ``second[i] ``=` `max``(second[i], j)``            ` `    ``# traverse for every elements and checks``    ``# the maximum N that is present in both``    ``# the arrays``    ` `    ``i ``=` `N``-``1``    ``while` `i>``=` `0``:``        ``if` `(first[i]>``0` `and` `second[i]>``0``):``            ``break``        ``i ``-``=` `1``    ` `    ``print``( ``str``(first[i]) ``+` `" "` `+` `str``(second[i]))` `# driver program to test the above function``if` `__name__ ``=``=` `"__main__"``:``    ``a ``=` `[ ``3``, ``1``, ``4``, ``2``, ``8` `]``    ``b ``=` `[ ``5``, ``2``, ``12``, ``8``, ``3` `]``    ``n ``=` `len``(a)` `    ``# Maximum possible value of elements``    ``# in both arrays.``    ``N ``=` `20``    ``gcdMax(a, b, n, N)` `# this code is contributed by ChitraNayal`

## C#

 `// C# program to find``// maximum GCD pair``// from two arrays``using` `System;` `class` `GFG``{``// Find the maximum GCD``// pair with maximum sum``static` `void` `gcdMax(``int``[] a, ``int``[] b,``                   ``int` `n, ``int` `N)``{``    ``// array to keep a count``    ``// of existing elements``    ``int``[] cnt = ``new` `int``[N];` `    ``// first[i] and second[i]``    ``// are going to store``    ``// maximum multiples of``    ``// i in a[] and b[]``    ``// respectively.``    ``int``[] first = ``new` `int``[N];``    ``int``[] second = ``new` `int``[N];` `    ``// traverse through the``    ``// first array to mark``    ``// the elements in cnt``    ``for` `(``int` `i = 0; i < n; ++i)``        ``cnt[a[i]] = 1;` `    ``// Find maximum multiple``    ``// of every number in``    ``// first array``    ``for` `(``int` `i = 1; i < N; ++i)``        ``for` `(``int` `j = i; j < N; j += i)``            ``if` `(cnt[j] > 0)``                ``first[i] = Math.Max(first[i], j);` `    ``// 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``    ``cnt = ``new` `int``[N];``    ``for` `(``int` `i = 0; i < n; ++i)``        ``cnt[b[i]] = 1;``    ``for` `(``int` `i = 1; i < N; ++i)``        ``for` `(``int` `j = i; j < N; j += i)` `            ``// if the multiple is present``            ``// in the second array then``            ``// store the max of number or``            ``// the pre-existing element``            ``if` `(cnt[j] > 0)``                ``second[i] = Math.Max(second[i], j);` `    ``// traverse for every``    ``// elements and checks``    ``// the maximum N that``    ``// is present in both``    ``// the arrays``    ``int` `x;``    ``for` `(x = N - 1; x >= 0; x--)``        ``if` `(first[x] > 0 &&``            ``second[x] > 0)``            ``break``;` `    ``Console.WriteLine(first[x] +``                      ``" "` `+ second[x]);``}` `// Driver Code``static` `int` `Main()``{``    ``int``[] a = { 3, 1, 4, 2, 8 };``    ``int``[] b = { 5, 2, 12, 8, 3 };``    ``int` `n = a.Length;` `    ``// Maximum possible``    ``// value of elements``    ``// in both arrays.``    ``int` `N = 20;` `    ``gcdMax(a, b, n, N);``    ``return` `0;``}``}` `// This code is contributed``// by mits`

## PHP

 `= 0; ``\$x``--)``        ``if` `(``\$first``[``\$x``] && ``\$second``[``\$x``])``            ``break``;` `        ``echo` `\$first``[``\$x``] . ``" "` `.``             ``\$second``[``\$x``] . ``"\n"``;``}` `// Driver code``\$a` `= ``array``(3, 1, 4, 2, 8);``\$b` `= ``array``(5, 2, 12, 8, 3);``\$n` `= sizeof(``\$a``);` `// Maximum possible value``// of elements in both arrays.``\$N` `= 20;` `gcdMax(``\$a``, ``\$b``, ``\$n``, ``\$N``);` `// This code is contributed``// by mits``?>`

## Javascript

 ``

Output :

`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.
This article is contributed by Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up