Array with GCD of any of its subset belongs to the given array | Function to return gcd of a and b ; Function to find gcd of array of numbers ; Function to generate the array with required constraints . ; computing GCD of the given set ; Solution exists if GCD of array is equal to the minimum element of the array ; Printing the built array ; Taking in the input and initializing the set STL set in cpp has a property that it maintains the elements in sorted order , thus we do not need to sort them externally ; Calling the computing function .
function gcd ( a , b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } function findGCD ( arr , n ) { var result = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) result = gcd ( arr [ i ] , result ) ; return result ; } function compute ( arr , n ) { var answer = new Array ( ) ; var GCD_of_array = findGCD ( arr , n ) ; if ( GCD_of_array == arr [ 0 ] ) { answer . add ( arr [ 0 ] ) ; for ( i = 1 ; i < n ; i ++ ) { answer . add ( arr [ 0 ] ) ; answer . add ( arr [ i ] ) ; } for ( var i = 0 ; i < answer . length ; i ++ ) document . write ( answer [ i ] + " " ) ; } else document . write ( " " + " " ) ; } var n = 3 ; var input = [ 2 , 5 , 6 , 7 , 11 ] ; compute ( input , n ) ;