Smallest subsequence having GCD equal to GCD of given array | Function to calculate gcd of two numbers ; 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
function gcd ( a , b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } function printSmallSub ( arr , N ) { let gcdArr = 0 ; for ( let i = 0 ; i < N ; i ++ ) { gcdArr = gcd ( gcdArr , arr [ i ] ) ; } for ( let i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == gcdArr ) { document . write ( arr [ i ] + " " ) ; return ; } } for ( let i = 0 ; i < N ; i ++ ) { for ( let j = i + 1 ; j < N ; j ++ ) { if ( gcd ( arr [ i ] , arr [ j ] ) == gcdArr ) { document . write ( arr [ i ] + " " + arr [ j ] ) ; return ; } } } } let arr = [ 4 , 6 , 12 ] ; let N = arr . length ; printSmallSub ( arr , N ) ;