Generate an N | Function to calculate GCD of two integers ; Function to calculate GCD of a given array ; Utility function to check for all the possible combinations ; If an N - length sequence is obtained ; If GCD of the sequence is K ; Otherwise ; Add an element from the first array ; Recursively proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Add an element from the second array ; Recursive proceed further ; If combination satisfies the necessary condition ; Remove the element from the combination ; Function to check all the possible combinations ; Stores the subsequence ; If GCD is not equal to K for any combination ; Given arrays ; Given value of K ; Function call to generate the required subsequence
function GCD ( a , b ) { if ( b < 1 ) return a ; return GCD ( b , a % b ) ; } function GCDArr ( a ) { let ans = a [ 0 ] ; for ( let i = 0 ; i < a . length ; i ++ ) ans = GCD ( ans , a [ i ] ) ; return ans ; } function findSubseqUtil ( a , b , ans , k , i ) { if ( ans . length == a . length ) { if ( GCDArr ( ans ) == k ) { document . write ( " " ) ; let m = ans . length ; for ( let j = 0 ; j < m - 1 ; j ++ ) document . write ( ans [ j ] + " " ) ; document . write ( ans [ m - 1 ] + " " ) ; return true ; } else return false ; } ans . push ( a [ i ] ) ; let temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp ) return true ; ans . splice ( ans . length - 1 , 1 ) ; ans . push ( b [ i ] ) ; temp = findSubseqUtil ( a , b , ans , k , i + 1 ) ; if ( temp ) return true ; ans . splice ( ans . length - 1 , 1 ) ; return false ; } function findSubseq ( A , B , K , i ) { let ans = [ ] ; findSubseqUtil ( A , B , ans , K , i ) ; if ( ans . length < 1 ) document . write ( - 1 ) ; } let A = [ 5 , 3 , 6 , 2 , 9 ] ; let B = [ 21 , 7 , 14 , 12 , 28 ] ; let K = 3 ; findSubseq ( A , B , K , 0 ) ;