Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Array with GCD of any of its subset belongs to the given array?
In this problem, we need to generate an array such that the GCD of any subset of that array belongs to the given set of elements. The constraint is that the generated array should not be more than thrice the length of the given set.
Syntax
int gcd(int a, int b); int getGCDofArray(int arr[], int n); void generateArray(int arr[], int n);
Algorithm
The algorithm works as follows −
- Calculate the GCD of the entire given array
- Check if this GCD equals the minimum element of the array
- If yes, insert the GCD between each element to form the result array
- If no, such an array cannot be formed
Example
Let's implement this algorithm in C −
#include <stdio.h>
int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
int getGCDofArray(int arr[], int n) {
int result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);
return result;
}
void generateArray(int arr[], int n) {
int answer[100];
int idx = 0;
int GCD_of_array = getGCDofArray(arr, n);
if (GCD_of_array == arr[0]) {
answer[idx++] = arr[0];
for (int i = 1; i < n; i++) {
answer[idx++] = arr[0];
answer[idx++] = arr[i];
}
printf("Generated array: ");
for (int i = 0; i < idx; i++)
printf("%d ", answer[i]);
printf("<br>");
} else {
printf("No array can be built<br>");
}
}
int main() {
int n = 4;
int data[] = {2, 4, 6, 12};
printf("Given set: ");
for (int i = 0; i < n; i++) {
printf("%d ", data[i]);
}
printf("<br>");
generateArray(data, n);
return 0;
}
Given set: 2 4 6 12 Generated array: 2 2 4 2 6 2 12
How It Works
In the example above −
- Given set: {2, 4, 6, 12}
- GCD of the entire set = gcd(2, 4, 6, 12) = 2
- Minimum element = 2
- Since GCD equals minimum element, we can form the array
- Result: {2, 2, 4, 2, 6, 2, 12} where 2 is inserted between elements
Conclusion
This algorithm ensures that any subset's GCD will belong to the original set by strategically placing the GCD value between elements. The solution works only when the array's GCD equals its minimum element.
Advertisements
