Generate an N | JavaScript program for the above approach ; Function to calculate GCD of given array ; Utility function to check for all the combinations ; If a sequence of size N is obtained ; If gcd of current combination is K ; If current element from first array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; If current element from second array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; Function to check for all possible combinations ; Stores the subsequence ; If GCD of any sequence is not equal to K ; Given arrays ; size of the array ; Given value of K ; Function call to generate a subsequence whose GCD is K
function GCD ( a , b ) { if ( b === 0 ) return a ; return GCD ( b , a % b ) ; } function GCDArr ( a ) { var ans = a [ 0 ] ; for ( const val of a ) { ans = GCD ( ans , val ) ; } return ans ; } function findSubseqUtil ( a , b , ans , k , i , N ) { if ( ans . length === N ) { if ( GCDArr ( ans ) === k ) { document . write ( " " + ans + " " ) ; return true ; } else { return false ; } } if ( a [ i ] % k === 0 ) { ans . push ( a [ i ] ) ; var temp = findSubseqUtil ( a , b , ans , k , i + 1 , N ) ; if ( temp === true ) return true ; delete ans [ ans . length - 1 ] ; } if ( b [ i ] % k === 0 ) { ans . push ( b [ i ] ) ; var temp = findSubseqUtil ( a , b , ans , k , i + 1 , N ) ; if ( temp === true ) return true ; delete ans [ ans . length - 1 ] ; } return false ; } function findSubseq ( A , B , K , i , N ) { var ans = [ ] ; var ret = findSubseqUtil ( A , B , ans , K , i , N ) ; if ( ret === false ) document . write ( - 1 ) ; } var A = [ 5 , 3 , 6 , 2 , 9 ] ; var B = [ 21 , 7 , 14 , 12 , 28 ] ; var N = A . length ; var K = 3 ; findSubseq ( A , B , K , 0 , N ) ;