Smallest subsequence having GCD equal to GCD of given array | C ++ program to implement the above approach ; Function to print the smallest subsequence that satisfies the condition ; Stores gcd of the array . ; Traverse the given array ; Update gcdArr ; Traverse the given array . ; If current element equal to gcd of array . ; Generate all possible pairs . ; If gcd of current pair equal to gcdArr ; Print current pair of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSmallSub ( int arr [ ] , int N ) { int gcdArr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { gcdArr = __gcd ( gcdArr , arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == gcdArr ) { cout << arr [ i ] << " ▁ " ; return ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( __gcd ( arr [ i ] , arr [ j ] ) == gcdArr ) { cout << arr [ i ] << " ▁ " << arr [ j ] ; return ; } } } } int main ( ) { int arr [ ] = { 4 , 6 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printSmallSub ( arr , N ) ; }