![]() |
VOOZH | about |
Given an array arr[] of size n, containing positive integers, find the maximum possible GCD among all pairs of elements in the array.
Examples:
Input: arr[] = [1, 2, 3, 4, 5]
Output: 2
Explanation: The pair (2, 4) has GCD 2, which is the maximum among all pairs.Input: arr[] = [2, 4, 8, 12]
Output: 4
Explanation: The pair (4, 8) or (4, 12) has GCD 4, which is the maximum possible among all pairs in the array.
Table of Content
The simplest idea is to check the GCD of every possible pair in the array and keep track of the maximum GCD obtained.
4
The idea is based on a simple observation that a number can be the GCD of a pair only if it divides them. So instead of checking all pairs, we focus on divisors of each element. For every number in the array, we find all its divisors and maintain a count array count[i], where count[i] stores how many array elements are divisible by i.
Consider array: arr[] = [2, 4, 8, 12]
Maximum element: 12 -> create count[0...12] = 0.
Step 1: Find divisors and update count
Step 2: Updated count values
Step 3: Final count array
Index :1 2 3 4 5 6 7 8 9 10 11 12
Count :4 4 1 3 0 1 0 1 0 0 0 1
Step 4: Traverse from largest to smallest
Since count[4] > 1, 4 divides at least two numbers. So, the maximum possible GCD is: 4
4
The approach is based on a key observation: if a number g is the GCD of a pair, then both numbers must be divisible by g. So, instead of checking all pairs, we focus on possible GCD values. We first build a frequency array freq[], where freq[i] stores the count of occurrences of i in the array.
Now, we iterate over all possible values of g from the largest element down to 1 and check all multiples of g (i.e., g, 2g, 3g, ...) using the frequency array. If the total count of numbers divisible by g is at least 2, then g can be the GCD of some pair. Since we process values in decreasing order, the first valid g encountered is the maximum possible GCD.
Consider array: arr = [2, 4, 8, 12]
Step 1: Build Frequency Array
(All other values have frequency 0)
Step 2: Check from Largest to Smallest
Since g = 4 is the first value from the top having count ≥ 2, so Maximum GCD = 4
4