Given an array A of size N, our task is to find the length of the largest subset such that all elements in the subset are pairwise coprime that is for any two elements x and y where x and y are not same the gcd(x, y) is equal to 1.
Note: All array elements are <= 50.
Examples:
Input: A = [2, 5, 2, 5, 2]
Output: 2
Explanation:
Largest subset satisfying the condition is: {2, 5}Input: A = [2, 3, 13, 5, 14, 6, 7, 11]
Output: 6
Naive Approach:
To solve the problem mentioned above we have to generate all subsets, and for each subset check whether the given condition holds or not. But this method takes O(N2 * 2N) time and can be optimized further.
Below is the implementation of the above approach:
C++
// CPP implementation to Find the length of the Largest // subset such that all elements are Pairwise Coprime #include <bits/stdc++.h> using namespace std; // Function to find the largest subset possible int largestSubset(int a[], int n) { int answer = 0; // Iterate through all the subsets for (int i = 1; i < (1 << n); i++) { vector<int> subset; /* Check if jth bit in the counter is set */ for (int j = 0; j < n; j++) { if (i & (1 << j)) subset.push_back(a[j]); } bool flag = true; for (int j = 0; j < subset.size(); j++) { for (int k = j + 1; k < subset.size(); k++) { // Check if the gcd is not equal to 1 if (__gcd(subset[j], subset[k]) != 1) flag = false; } } if (flag == true) // Update the answer with maximum value answer = max(answer, (int)subset.size()); } // Return the final result return answer; } // Driver code int main() { int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = sizeof(A) / sizeof(A[0]); cout << largestSubset(A, N); return 0; } |
Python3
# Python3 implementation to Find # the length of the Largest subset # such that all elements are Pairwise Coprime import math # Function to find the largest subset possible def largestSubset(a, n): answer = 0 # Iterate through all the subsets for i in range(1, (1 << n)): subset = [] # Check if jth bit in the counter is set for j in range(0, n): if (i & (1 << j)): subset.insert(j, a[j]) flag = True for j in range(0, len(subset)): for k in range(j + 1, len(subset)): # Check if the gcd is not equal to 1 if (math.gcd(subset[j], subset[k]) != 1) : flag = False if (flag == True): # Update the answer with maximum value answer = max(answer, len(subset)) # Return the final result return answer # Driver code A = [ 2, 3, 13, 5, 14, 6, 7, 11 ] N = len(A) print(largestSubset(A, N)) # This code is contributed by Sanjit_Prasad |
6
Efficient Approach:
The above method can be optimized and the approach depends on the fact that there are only 15 prime numbers in the first 50 natural numbers. So all the numbers in array will have prime factors among these 15 numbers only. We will use Bitmasking and Dynamic Programming to optimize the problem.
- Since there are 15 primes only, consider a 15-bit representation of every number where each bit is 1 if that index of prime is a factor of that number. We will index prime numbers by 0 indexing, which means 2 at 0th position 3 at index 1 and so on.
- An integer variable ‘mask‘ indicates the prime factors which have already occurred in the subset. If i’th bit is set in the mask, then i’th prime factor has occurred, otherwise not.
- At each step of recurrence relation, the element can either be included in the subset or cannot be included. If the element is not included in the subarray, then simply move to the next index. If it is included, change the mask by setting all the bits corresponding to the current element’s prime factors, ON in the mask. The current element can only be included, if all of its prime factors have not occurred previously.
- This condition will be satisfied only if the bits corresponding to the current element’s digits in the mask are OFF.
If we draw the complete recursion tree, we can observe that many subproblems are being solved which were occurring again and again. So we use a table dp[][] such that for every index dp[i][j], i is the position of the element in the array, and j is the mask.
Below is the implementation of the above approach:
// CPP implementation to Find the length of the Largest // subset such that all elements are Pairwise Coprime #include <bits/stdc++.h> using namespace std; // Dynamic programming table int dp[5000][(1 << 10) + 5]; // Function to obtain the mask for any integer int getmask(int val) { int mask = 0; // List of prime numbers till 50 int prime[15] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; // Iterate through all prime numbers to obtain the mask for (int i = 0; i < 15; i++) { if (val % prime[i] == 0) { // Set this prime's bit ON in the mask mask = mask | (1 << i); } } // Return the mask value return mask; } // Function to count the number of ways int calculate(int pos, int mask, int a[], int n) { if (pos == n || mask == (1 << n - 1)) return 0; // Check if subproblem has been solved if (dp[pos][mask] != -1) return dp[pos][mask]; int size = 0; // Excluding current element in the subset size = max(size, calculate(pos + 1, mask, a, n)); // Check if there are no common prime factors // then only this element can be included if ((getmask(a[pos]) & mask) == 0) { // Calculate the new mask if this element is included int new_mask = (mask | (getmask(a[pos]))); size = max(size, 1 + calculate(pos + 1, new_mask, a, n)); } // Store and return the answer return dp[pos][mask] = size; } // Function to find the count of // subarray with all digits unique int largestSubset(int a[], int n) { // Intializing dp memset(dp, -1, sizeof(dp)); return calculate(0, 0, a, n); } // Driver code int main() { int A[] = { 2, 3, 13, 5, 14, 6, 7, 11 }; int N = sizeof(A) / sizeof(A[0]); cout << largestSubset(A, N); return 0; } |
6
Time Complexity: O(N * 15 * 215)
Recommended Posts:
- Length of the longest increasing subsequence such that no two adjacent elements are coprime
- Find the length of largest subarray in which all elements are Autobiographical Numbers
- Find a non empty subset in an array of N integers such that sum of elements of subset is divisible by N
- Largest subset whose all elements are Fibonacci numbers
- Find the Largest divisor Subset in the Array
- Find the winner by adding Pairwise difference of elements in the array until Possible
- Largest Coprime Set Between two integers
- Largest number less than or equal to N/2 which is coprime to N
- Length of largest subarray whose all elements Powerful number
- Length of largest subarray whose all elements are Perfect Number
- Largest possible Subset from an Array such that no element is K times any other element in the Subset
- Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
- Minimum number of elements to be removed so that pairwise consecutive elements are same
- Largest Subset with GCD 1
- Find the k largest numbers after deleting the given elements
- Largest divisible subset in array
- Largest divisible pairs subset
- Size of the largest divisible subset in an Array
- Largest subset having with sum less than equal to sum of respective indices
- Largest subset with M as smallest missing number
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 : Sanjit_Prasad


