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


Here we will see one interesting problem. There is a set of N elements. We have to generate an array such that the GCD of any subset of that array lies in the given set of elements. And another constraint is that the generated array should not be more than thrice the length of the set of the GCD. For example, if there are 4 numbers {2, 4, 6, 12}, then one array will be {2, 2, 4, 2, 6, 2, 12}

To solve this problem, we have to sort the list at first, then if the GCD is the same as the minimum element of the given set, then create array just by putting GCD between each element. Otherwise, no array can be formed.

Algorithm

generateArray(arr, n)

Begin
   answer := empty array
   gcd := gcd of array arr
   if gcd is same as the min element of arr, then
      for each element e in arr, do
         append gcd into answer
         append e into answer
      done
      display answer
   else
      array cannot be formed
   end if
End

Example

#include<iostream>
#include<vector>
#include<set>
using namespace std;
int gcd(int a, int b) {
   if (a == 0)
      return b;
   return gcd(b % a, a);
}
int getGCDofArray(vector<int> arr) {
   int result = arr[0];
   for (int i = 1; i < arr.size(); i++)
      result = gcd(arr[i], result);
   return result;
}
void generateArray(vector<int> arr) {
   vector<int> answer;
   int GCD_of_array = getGCDofArray(arr);
   if(GCD_of_array == arr[0]) { //if gcd is same as minimum element
      answer.push_back(arr[0]);
      for(int i = 1; i < arr.size(); i++) { //push min before each
         element
         answer.push_back(arr[0]);
         answer.push_back(arr[i]);
      }
      for (int i = 0; i < answer.size(); i++)
      cout << answer[i] << " ";
   }
   else
   cout << "No array can be build";
}
int main() {
   int n = 4;
   int data[]= {2, 4, 6, 12};
   set<int> GCD(data, data + n);
   vector<int> arr;
   set<int>::iterator it;
   for(it = GCD.begin(); it!= GCD.end(); ++it)
      arr.push_back(*it);
   generateArray(arr);
}

Output

2 2 4 2 6 2 12

Updated on: 01-Aug-2019

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements