
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find pair with maximum GCD in an array in C++
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
#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
- Related Articles
- Find any pair with given GCD and LCM in C++
- Print pair with maximum AND value in an array in C Program.
- Find a pair with maximum product in array of Integers in C++
- Find a pair from the given array with maximum nCr value in Python
- Find a pair from the given array with maximum nCr value in C++
- Find original numbers from gcd() every pair in Python
- Find original numbers from gcd() every pair in C++
- Maximum bitwise AND value of a pair in an array in C++
- Find Maximum difference pair in Python
- Queries to find maximum product pair in range with updates in C++
- GCD of an array of numbers in java
- Maximum GCD of N integers with given product in C++
- Program to find maximum XOR with an element from array in Python
- Find pair with maximum difference in any column of a Matrix in C++
- Subsequence of size k with maximum possible GCD

Advertisements