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.
C++
#include <bits/stdc++.h>
using namespace std;
int gcd( int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int main() {
int a[] = {12, 18, 24};
int b[] = {36, 8, 72};
int m = sizeof (a)/ sizeof (a[0]);
int n = sizeof (b)/ sizeof (b[0]);
int max_gcd = INT_MIN;
int num1, num2;
for ( int i=0; i<m; i++) {
for ( int j=0; j<n; j++) {
int g = gcd(a[i], b[j]);
if (g > max_gcd) {
max_gcd = g;
num1 = a[i];
num2 = b[j];
}
}
}
cout << "Pair with greatest GCD: (" << num1 << ", " << num2 << ") with GCD: " << max_gcd << endl;
return 0;
}
|
Java
import java.lang.Math;
public class GCD {
public static int gcd( int a, int b)
{
if (b == 0 ) {
return a;
}
return gcd(b, a % b);
}
public static void main(String[] args)
{
int [] a = { 12 , 18 , 24 };
int [] b = { 36 , 8 , 72 };
int max_gcd = Integer.MIN_VALUE;
Integer num1 = null ;
Integer num2 = null ;
for ( int i = 0 ; i < a.length; i++) {
for ( int j = 0 ; j < b.length; j++) {
int g = gcd(a[i], b[j]);
if (g > max_gcd) {
max_gcd = g;
num1 = a[i];
num2 = b[j];
}
}
}
System.out.println( "Pair with greatest GCD: ("
+ num1 + ", " + num2
+ ") with GCD: " + max_gcd);
}
}
|
Python3
import math
def gcd(a, b):
if b = = 0 :
return a
return gcd(b, a % b)
a = [ 12 , 18 , 24 ]
b = [ 36 , 8 , 72 ]
max_gcd = float ( "-inf" )
num1, num2 = None , None
for i in range ( len (a)):
for j in range ( len (b)):
g = gcd(a[i], b[j])
if g > max_gcd:
max_gcd = g
num1 = a[i]
num2 = b[j]
print (f "Pair with greatest GCD: ({num1}, {num2}) with GCD: {max_gcd}" )
|
C#
using System;
class MainClass {
static int GCD( int a, int b) {
if (b == 0) return a;
return GCD(b, a % b);
}
static void Main() {
int [] a = new int [] {12, 18, 24};
int [] b = new int [] {36, 8, 72};
int m = a.Length;
int n = b.Length;
int max_gcd = int .MinValue;
int num1 = 0, num2 = 0;
for ( int i=0; i<m; i++) {
for ( int j=0; j<n; j++) {
int g = GCD(a[i], b[j]);
if (g > max_gcd) {
max_gcd = g;
num1 = a[i];
num2 = b[j];
}
}
}
Console.WriteLine( "Pair with greatest GCD: ({0}, {1}) with GCD: {2}" , num1, num2, max_gcd);
}
}
|
Javascript
function gcd(a, b) {
if (b == 0) return a;
return gcd(b, a % b);
}
let a = [12, 18, 24];
let b = [36, 8, 72];
let m = a.length;
let n = b.length;
let max_gcd = Number.MIN_SAFE_INTEGER;
let num1, num2;
for (let i=0; i<m; i++) {
for (let j=0; j<n; j++) {
let g = gcd(a[i], b[j]);
if (g > max_gcd) {
max_gcd = g;
num1 = a[i];
num2 = b[j];
}
}
}
console.log( "Pair with greatest GCD: (" + num1 + ", " + num2 + ") with GCD: " + max_gcd);
|
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.
- A cnt array to mark the presence of array elements.
- 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.
- Step 1 and 2 is repeated for the other array also.
- 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++
#include <bits/stdc++.h>
using namespace std;
void gcdMax( int a[], int b[], int n, int N)
{
int cnt[N] = { 0 };
int first[N] = { 0 }, second[N] = { 0 };
for ( int i = 0; i < n; ++i)
cnt[a[i]] = 1;
for ( int i = 1; i < N; ++i)
for ( int j = i; j < N; j += i)
if (cnt[j])
first[i] = max(first[i], j);
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 (cnt[j])
second[i] = max(second[i], j);
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;
}
int main()
{
int a[] = { 3, 1, 4, 2, 8 };
int b[] = { 5, 2, 12, 8, 3 };
int n = sizeof (a) / sizeof (a[0]);
int N = 20;
gcdMax(a, b, n, N);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static void gcdMax( int [] a, int [] b,
int n, int N)
{
int [] cnt = new int [N];
int [] first = new int [N];
int [] second = new int [N];
for ( int i = 0 ; i < n; ++i)
cnt[a[i]] = 1 ;
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);
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 (cnt[j] > 0 )
second[i] = Math.max(second[i], j);
int x;
for (x = N - 1 ; x >= 0 ; x--)
if (first[x] > 0 &&
second[x] > 0 )
break ;
System.out.println(first[x] + " " +
second[x]);
}
public static void main(String[] args)
{
int [] a = { 3 , 1 , 4 , 2 , 8 };
int [] b = { 5 , 2 , 12 , 8 , 3 };
int n = a.length;
int N = 20 ;
gcdMax(a, b, n, N);
}
}
|
Python3
def gcdMax(a, b, n, N):
cnt = [ 0 ] * N
first = [ 0 ] * N
second = [ 0 ] * N
for i in range (n):
cnt[a[i]] = 1
for i in range ( 1 ,N):
for j in range (i,N,i):
if (cnt[j]):
first[i] = max (first[i], j)
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 (cnt[j]> 0 ):
second[i] = max (second[i], j)
i = N - 1
while i> = 0 :
if (first[i]> 0 and second[i]> 0 ):
break
i - = 1
print ( str (first[i]) + " " + str (second[i]))
if __name__ = = "__main__" :
a = [ 3 , 1 , 4 , 2 , 8 ]
b = [ 5 , 2 , 12 , 8 , 3 ]
n = len (a)
N = 20
gcdMax(a, b, n, N)
|
C#
using System;
class GFG
{
static void gcdMax( int [] a, int [] b,
int n, int N)
{
int [] cnt = new int [N];
int [] first = new int [N];
int [] second = new int [N];
for ( int i = 0; i < n; ++i)
cnt[a[i]] = 1;
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);
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 (cnt[j] > 0)
second[i] = Math.Max(second[i], j);
int x;
for (x = N - 1; x >= 0; x--)
if (first[x] > 0 &&
second[x] > 0)
break ;
Console.WriteLine(first[x] +
" " + second[x]);
}
static int Main()
{
int [] a = { 3, 1, 4, 2, 8 };
int [] b = { 5, 2, 12, 8, 3 };
int n = a.Length;
int N = 20;
gcdMax(a, b, n, N);
return 0;
}
}
|
PHP
<?php
function gcdMax( $a , $b , $n , $N )
{
$cnt = array_fill (0, $N , 0);
$first = array_fill (0, $N , 0);
$second = array_fill (0, $N , 0);
for ( $i = 0; $i < $n ; ++ $i )
$cnt [ $a [ $i ]] = 1;
for ( $i = 1; $i < $N ; ++ $i )
for ( $j = $i ; $j < $N ; $j += $i )
if ( $cnt [ $j ])
$first [ $i ] = max( $first [ $i ], $j );
$cnt = array_fill (0, $N , 0);
for ( $i = 0; $i < $n ; $i ++)
$cnt [ $b [ $i ]] = 1;
for ( $i = 1; $i < $N ; $i ++)
for ( $j = $i ; $j < $N ; $j += $i )
if ( $cnt [ $j ])
$second [ $i ] = max( $second [ $i ], $j );
$x = $N - 1;
for (; $x >= 0; $x --)
if ( $first [ $x ] && $second [ $x ])
break ;
echo $first [ $x ] . " " .
$second [ $x ] . "\n" ;
}
$a = array (3, 1, 4, 2, 8);
$b = array (5, 2, 12, 8, 3);
$n = sizeof( $a );
$N = 20;
gcdMax( $a , $b , $n , $N );
?>
|
Javascript
<script>
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);
</script>
|
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.
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
18 Sep, 2023
Like Article
Save Article