Find pair with maximum GCD in an array | C ++ Code to find pair with maximum GCD in an array ; function to find GCD of pair with max GCD in the array ; Computing highest element ; Array to store the count of divisors i . e . Potential GCDs ; Iterating over every element ; Calculating all the divisors ; Divisor found ; Incrementing count for divisor ; Element / divisor is also a divisor Checking if both divisors are not same ; Checking the highest potential GCD ; If this divisor can divide at least 2 numbers , it is a GCD of at least 1 pair ; Driver code ; Array in which pair with max GCD is to be found ; Size of array
#include <bits/stdc++.h> NEW_LINE 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 ; }