We are given an array of positive integers. Find the pair in array with maximum GCD.
Examples:
Input : arr[] : { 1 2 3 4 5 }
Output : 2
Explanation : Pair {2, 4} has GCD 2 which is highest. Other pairs have a GCD of 1.
Input : arr[] : { 2 3 4 8 8 11 12 }
Output : 8
Explanation : Pair {8, 8} has GCD 8 which is highest.
Brute Force Approach:
The brute force approach to solve this problem is to generate all possible pairs of elements from the array and calculate their GCD. Then, we can find the pair with the maximum GCD among these pairs.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxGCD( int arr[], int n)
{
int maxGcd = 0;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
int gcd = __gcd(arr[i], arr[j]);
maxGcd = max(maxGcd, gcd);
}
}
return maxGcd;
}
int main()
{
int arr[] = { 1, 2, 4, 8, 8, 12 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findMaxGCD(arr,n);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int findMaxGCD( int [] arr, int n) {
int maxGcd = 0 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
int gcd = gcd(arr[i], arr[j]);
maxGcd = Math.max(maxGcd, gcd);
}
}
return maxGcd;
}
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 [] arr = { 1 , 2 , 4 , 8 , 8 , 12 };
int n = arr.length;
System.out.println(findMaxGCD(arr, n));
}
}
|
Python3
import math
def findMaxGCD(arr, n):
maxGcd = 0
for i in range (n):
for j in range (i + 1 , n):
gcd = math.gcd(arr[i], arr[j])
maxGcd = max (maxGcd, gcd)
return maxGcd
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 8 , 8 , 12 ]
n = len (arr)
print (findMaxGCD(arr,n))
|
C#
using System;
class Program
{
static int FindMaxGCD( int [] arr)
{
int maxGcd = 0;
int n = arr.Length;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
int gcd = GCD(arr[i], arr[j]);
maxGcd = Math.Max(maxGcd, gcd);
}
}
return maxGcd;
}
static int GCD( int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
static void Main()
{
int [] arr = { 1, 2, 4, 8, 8, 12 };
int maxGCD = FindMaxGCD(arr);
Console.WriteLine(maxGCD);
}
}
|
Javascript
function findMaxGCD(arr) {
let maxGcd = 0;
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
const gcd = findGCD(arr[i], arr[j]);
maxGcd = Math.max(maxGcd, gcd);
}
}
return maxGcd;
}
function findGCD(a, b) {
if (b === 0) {
return a;
}
return findGCD(b, a % b);
}
const arr = [1, 2, 4, 8, 8, 12];
const result = findMaxGCD(arr);
console.log(result);
|
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Method 2 : (Efficient) In this method, we maintain a count array to store the count of divisors of every element. We will traverse the given array and for every element, we will calculate its divisors and increment at the index of count array. The process of computing divisors will take O(sqrt(arr[i])) time, where arr[i] is element in the given array at index i. After the whole traversal, we can simply traverse the count array from last index to index 1. If we found an index with a value greater than 1, then this means that it is a divisor of 2 elements and also the max GCD.
Below is the implementation of above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxGCD( int arr[], int n)
{
int high = 0;
for ( int i = 0; i < n; i++)
high = max(high, arr[i]);
int divisors[high + 1] = { 0 };
for ( int i = 0; i < n; i++)
{
for ( int j = 1; j <= sqrt (arr[i]); j++)
{
if (arr[i] % j == 0)
{
divisors[j]++;
if (j != arr[i] / j)
divisors[arr[i] / j]++;
}
}
}
for ( int i = high; i >= 1; i--)
if (divisors[i] > 1)
return i;
}
int main()
{
int arr[] = { 1, 2, 4, 8, 8, 12 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findMaxGCD(arr,n);
return 0;
}
|
Java
public class GFG {
public static int findMaxGCD( int arr[], int n)
{
int high = 0 ;
for ( int i = 0 ; i < n; i++)
high = Math.max(high, arr[i]);
int divisors[] = new int [high + 1 ];
for ( int i = 0 ; i < n; i++)
{
for ( int j = 1 ; j <= Math.sqrt(arr[i]); j++)
{
if (arr[i] % j == 0 )
{
divisors[j]++;
if (j != arr[i] / j)
divisors[arr[i] / j]++;
}
}
}
for ( int i = high; i >= 1 ; i--)
if (divisors[i] > 1 )
return i;
return 1 ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 8 , 8 , 12 };
int n = arr.length;
System.out.println(findMaxGCD(arr,n));
}
}
|
Python
import math
def findMaxGCD(arr, n):
high = 0
i = 0
while i < n:
high = max (high, arr[i])
i = i + 1
divisors = [ 0 ] * (high + 1 )
i = 0
while i < n:
j = 1
while j < = math.sqrt(arr[i]):
if (arr[i] % j = = 0 ):
divisors[j] = divisors[j] + 1
if (j ! = arr[i] / j):
divisors[arr[i] / j] = divisors[arr[i] / j] + 1
j = j + 1
i = i + 1
i = high
while i > = 1 :
if (divisors[i] > 1 ):
return i
i = i - 1
return 1
arr = [ 1 , 2 , 4 , 8 , 8 , 12 ]
n = len (arr)
print findMaxGCD(arr, n)
|
C#
using System;
class GFG {
public static int findMaxGCD( int []arr,
int n)
{
int high = 0;
for ( int i = 0; i < n; i++)
high = Math.Max(high, arr[i]);
int []divisors = new int [high + 1];
for ( int i = 0; i < n; i++)
{
for ( int j = 1; j <=
Math.Sqrt(arr[i]); j++)
{
if (arr[i] % j == 0)
{
divisors[j]++;
if (j != arr[i] / j)
divisors[arr[i] / j]++;
}
}
}
for ( int i = high; i >= 1; i--)
if (divisors[i] > 1)
return i;
return 1;
}
public static void Main(String []args)
{
int []arr = {1, 2, 4, 8, 8, 12};
int n = arr.Length;
Console.WriteLine(findMaxGCD(arr,n));
}
}
|
Javascript
<script>
function findMaxGCD(arr , n)
{
var high = 0;
for ( var i = 0; i < n; i++)
high = Math.max(high, arr[i]);
var divisors =
Array.from({length: high + 1}, (_, i) => 0);
for ( var i = 0; i < n; i++)
{
for ( var j = 1; j <= Math.sqrt(arr[i]); j++)
{
if (arr[i] % j == 0)
{
divisors[j]++;
if (j != arr[i] / j)
divisors[arr[i] / j]++;
}
}
}
for ( var i = high; i >= 1; i--)
if (divisors[i] > 1)
return i;
return 1;
}
var arr = [ 1, 2, 4, 8, 8, 12 ];
var n = arr.length;
document.write(findMaxGCD(arr,n));
</script>
|
PHP
<?php
function findMaxGCD( $arr , $n )
{
$high = 0;
for ( $i = 0; $i < $n ; $i ++)
$high = max( $high , $arr [ $i ]);
$divisors = array_fill (0, $high + 1, 0);
for ( $i = 0; $i < $n ; $i ++)
{
for ( $j = 1;
$j <= (int)(sqrt( $arr [ $i ])); $j ++)
{
if ( $arr [ $i ] % $j == 0)
{
$divisors [ $j ]++;
if ( $j != (int)( $arr [ $i ] / $j ))
$divisors [(int)( $arr [ $i ] / $j )]++;
}
}
}
for ( $i = $high ; $i >= 1; $i --)
if ( $divisors [ $i ] > 1)
return $i ;
}
$arr = array ( 1, 2, 4, 8, 8, 12 );
$n = sizeof( $arr );
echo findMaxGCD( $arr , $n );
?>
|
Time Complexity: O(N * sqrt(arr[i]) + H) , where arr[i] denotes the element of the array and H denotes the largest number of the array.
Auxiliary Space: O(high), high is the maximum element in the array
Method 3 (Most Efficient): This approach is based on the idea of Sieve Of Eratosthenes.
First let’s solve a simpler problem, given a value X we have to tell whether a pair has a GCD equal to X. This can be done by checking that how many elements in the array are multiples of X. If the number of such multiples is greater than 1, then X will be a GCD of some pair.
Now for pair with maximum GCD, we maintain a count array of the original array. Our method is based on the above problem with Sieve-like approach for loop. Below is the step by step algorithm of this approach:
- Iterate ‘i’ from MAX (maximum array element) to 1.
- Iterate ‘j’ from ‘i’ to MAX. We will check if the count array is 1 at index ‘j’.
- Increment the index ‘j’ everytime with ‘i’. This way, we can check for
i, 2i, 3i, and so on.
- If we get 1 two times at count array that means 2 multiples of i exists. This makes it the highest GCD.
Below is the implementation of above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxGCD( int arr[], int n)
{
int high = 0;
for ( int i = 0; i < n; i++)
high = max(high, arr[i]);
int count[high + 1] = {0};
for ( int i = 0; i < n; i++)
count[arr[i]]++;
int counter = 0;
for ( int i = high; i >= 1; i--)
{
int j = i;
counter = 0;
while (j <= high)
{
if (count[j] >=2)
return j;
else if (count[j] == 1)
counter++;
j += i;
if (counter == 2)
return i;
}
}
}
int main()
{
int arr[] = { 1, 2, 4, 8, 8, 12 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findMaxGCD(arr, n);
return 0;
}
|
Java
class GFG {
public static int findMaxGCD( int arr[], int n)
{
int high = 0 ;
for ( int i = 0 ; i < n; i++)
high = Math.max(high, arr[i]);
int count[]= new int [high + 1 ];
for ( int i = 0 ; i < n; i++)
count[arr[i]]++;
int counter = 0 ;
for ( int i = high; i >= 1 ; i--)
{
int j = i;
while (j <= high)
{
if (count[j]> 0 )
counter+=count[j];
j += i;
if (counter == 2 )
return i;
}
counter= 0 ;
}
return 1 ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 8 , 8 , 12 };
int n = arr.length;
System.out.println(findMaxGCD(arr,n));
}
}
|
Python3
def findMaxGCD(arr, n) :
high = 0
for i in range ( 0 , n) :
high = max (high, arr[i])
count = [ 0 ] * (high + 1 )
for i in range ( 0 , n) :
count[arr[i]] + = 1
counter = 0
for i in range (high, 0 , - 1 ) :
j = i
while (j < = high) :
if (count[j] > 0 ) :
counter + = count[j]
j + = i
if (counter = = 2 ) :
return i
counter = 0
arr = [ 1 , 2 , 4 , 8 , 8 , 12 ]
n = len (arr)
print (findMaxGCD(arr, n))
|
C#
using System;
class GFG {
public static int findMaxGCD( int []arr,
int n)
{
int high = 0;
for ( int i = 0; i < n; i++)
high = Math.Max(high, arr[i]);
int []count= new int [high + 1];
for ( int i = 0; i < n; i++)
count[arr[i]]++;
int counter = 0;
for ( int i = high; i >= 1; i--)
{
int j = i;
while (j <= high)
{
if (count[j]>0)
counter+=count[j];
j += i;
if (counter == 2)
return i;
}
counter=0;
}
return 1;
}
public static void Main(String []args)
{
int []arr = {1, 2, 4, 8, 8, 12};
int n = arr.Length;
Console.WriteLine(findMaxGCD(arr,n));
}
}
|
Javascript
<script>
function findMaxGCD(arr , n)
{
var high = 0;
for (let i = 0; i < n; i++)
high = Math.max(high, arr[i]);
var count = Array(high + 1).fill(0);
for (let i = 0; i < n; i++)
count[arr[i]]++;
var counter = 0;
for (let i = high; i >= 1; i--)
{
var j = i;
while (j <= high)
{
if (count[j] > 0)
counter += count[j];
j += i;
if (counter == 2)
return i;
}
counter = 0;
}
return 1;
}
var arr = [ 1, 2, 4, 8, 8, 12 ];
var n = arr.length;
document.write(findMaxGCD(arr, n));
</script>
|
PHP
<?php
function findMaxGCD( $arr , $n )
{
$high = 0;
for ( $i = 0; $i < $n ; $i ++)
$high = max( $high , $arr [ $i ]);
$count = array_fill (0, $high + 1, 0);
for ( $i = 0; $i < $n ; $i ++)
$count [ $arr [ $i ]]++;
$counter = 0;
for ( $i = $high ; $i >= 1; $i --)
{
$j = $i ;
$counter = 0;
while ( $j <= $high )
{
if ( $count [ $j ] >= 2)
return $j ;
else if ( $count [ $j ] == 1)
$counter ++;
$j += $i ;
if ( $counter == 2)
return $i ;
}
}
}
$arr = array ( 1, 2, 4, 8, 8, 12 );
$n = count ( $arr );
print (findMaxGCD( $arr , $n ));
?>
|
Time Complexity: The time complexity of this approach is till an open problem known as the Dirichlet divisor problem.
Time Complexity: O(high2) , high is the maximum element in the array
Auxiliary Space: O(high), high is the maximum element in the 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!