Find pair with maximum GCD in an array in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of positive integers. Our task is to find pair of integers from the array, where the GCD value is maximum. Let A = {1, 2, 3, 4, 5}, then the output is 2. The pair (2, 4) has GCD 2, other GCD values are less than 2.

To solve this problem, we will maintain a count array to store the count of divisors of each element. The process of counting divisors will take O(sqrt(arr[i])) amount of time. After whole traversal, we can traverse the count array from last index to first index, then if we find some value where the element is greater than 1, then, this means that it is the divisor of 2 elements and also the max GCD.

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int getMaxGCD(int arr[], int n) {
   int high = 0;
   for (int i = 0; i < n; i++)
   high = max(high, arr[i]);
   int divisors[high + 1] = { 0 }; //array to store all gcd values
   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, 12 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Max GCD: " << getMaxGCD(arr,n);
}

Output

Max GCD: 4
raja
Published on 21-Oct-2019 13:39:05
Advertisements