Array with GCD of any of its subset belongs to the given array | C # implementation to generate the required 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 ; Driver Code ; 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 .
using System ; using System . Collections . Generic ; class GFG { static int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } static int findGCD ( List < int > arr , int n ) { int result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) result = gcd ( arr [ i ] , result ) ; return result ; } static void compute ( List < int > arr , int n ) { List < int > answer = new List < int > ( ) ; int GCD_of_array = findGCD ( arr , n ) ; if ( GCD_of_array == arr [ 0 ] ) { answer . Add ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { answer . Add ( arr [ 0 ] ) ; answer . Add ( arr [ i ] ) ; } for ( int i = 0 ; i < answer . Count ; i ++ ) Console . Write ( answer [ i ] + " ▁ " ) ; } else Console . Write ( " No ▁ array ▁ " + " can ▁ be ▁ build " ) ; } static void Main ( ) { int n = 3 ; int [ ] input = new int [ ] { 2 , 5 , 6 , 7 , 11 } ; HashSet < int > GCD = new HashSet < int > ( input ) ; List < int > arr = new List < int > ( ) ; foreach ( int b in GCD ) arr . Add ( b ) ; compute ( arr , n ) ; } }