Subsequence of size k with maximum possible GCD | CPP program to find subsequence of size k with maximum possible GCD . ; function to find GCD of sub sequence of size k 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 k numbers , it is a GCD of at least one sub sequence of size k ; Driver code ; Array in which sub sequence with size k with max GCD is to be found
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxGCD ( int arr [ ] , int n , int k ) { int high = * max_element ( arr , arr + n ) ; 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 ] >= k ) return i ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 8 , 12 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaxGCD ( arr , n , k ) ; return 0 ; }