Array with GCD of any of its subset belongs to the given array

Given a set of N elements such that N\in [1, 1000], task is to generate an array such that the GCD of any subset of the generated array lies in the given set of elements. The generated array should not be more than thrice the length of the set of the GCD.

Prerequisite : GCD of an Array | Subset of Array

Examples :

Input : 3
        1 2 7
Output :  1 1 2 1 7

Input : 4
        2 4 6 12
Output : 4 6 12

Input : 5
        2 5 6 7 11
Output : No array can be build

Explanation :
Calculate the GCD of an array or in this case a set. Now, first sort the given set of GCD. If the GCD of this set is equal to the minimum number of the given set, then just by putting this GCD between each number. But, if this GCD is not the minimum element of the given set, then unfortunately “no array can be build”.

[sourcecode language=”CPP”]
// C++ implementation to generate the
// required array
#include <bits/stdc++.h>
using namespace std;

// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}

// Function to find gcd of
// array of numbers
int findGCD(vector<int> arr, int n)
{
int result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}

// Function to generate the array
// with required constraints.
void compute(vector<int> arr, int n)
{
vector<int> answer;

// computing GCD of the given set
int GCD_of_array = findGCD(arr, n);

// Solution exists if GCD of array is equal
// to the minimum element of the array
if(GCD_of_array == arr[0])
{
answer.push_back(arr[0]);
for(int i = 1; i < n; i++)
{
answer.push_back(arr[0]);
answer.push_back(arr[i]);
}

// Printing the built array
for (int i = 0; i < answer.size(); i++)
cout << answer[i] << " ";
}
else
cout << "No array can be build";
}

// Driver function
int main()
{

// 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
int n = 3;
int input[]= {2, 5, 6, 7, 11};
set<int> GCD(input, input + n);
vector<int> arr;
set<int>::iterator it;

for(it = GCD.begin(); it!= GCD.end(); ++it)
arr.push_back(*it);

// Calling the computing function.
compute(arr,n);

return 0;
}
[/sourcecode]

Output:

No array can be build

Time Complexity : O(nlog(n)), where n is the size of array given.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : manishshaw1