Skip to content
Related Articles

Related Articles

Maximum Partitions such that any two numbers from two Subsets are co-prime

View Discussion
Improve Article
Save Article
  • Last Updated : 29 Aug, 2022
View Discussion
Improve Article
Save Article

Given an array arr[] of length N, the task is to find the maximum number of subsets that can be obtained from the given array such that the GCD of every a and b that belong to two different subsets is 1.

Example:

Input: arr[] = {2, 3, 4, 5, 6}
Output: 2

Explanation:  Divide array into 2 subset such as S1 = { 2, 3, 4, 6 },  
S2= { 5 }, gcd for every a and b such that a ∈ S1 and b ∈ S2  is 1 i.e. 
GCD(2, 5) = 1, GCD(3, 5) = 1, GCD(4, 5) = 1, GCD(6, 5) = 1. 
Hence maximum number of subsets is 2.

Input: arr[] = { 2, 5, 13, 9, 7, 25, 21, 6 }
Output: 3

Approach: 

The idea to solve this problem is:

For each element of the array find all the elements which belong to same subset. 

To do this find elements that are not coprime with it. Then for those new found elements repeat the same procedure. All those elements will belong to one set. Otherwise, there will be pair from different subsets which are not coprime.

Follow the below illustration for a better understanding.

Illustration:

Consider the array arr[] = {2, 3, 4, 5, 6}

For the value 2:
        => The non co-prime elements are {4, 6}.
        => So the group will consist of {2, 4, 6}.

For the values 4 and 6:
        => The non co-prime values with 4 and 6 are {2, 6} and {2, 3, 4}
        => {2, 6} are already visited.
        => The new value is 3.
        => The subset now is {2, 4, 6, 3}.

For the value 3:
        => The non co-prime values are {6}.
        => 6 already included in the subset.

The leftover element is 5:
        => There is no non co-prime value for this.
        => The new subset {5}.

Therefore two subsets can be formed {2, 4, 6, 3} and {5}.

The following steps should be taken to solve this problem:

  • Firstly, create two dictionaries, one for the number and another for the factors.
  • The first dictionary dic1 is used to check if the number is already present in the list or not.
  • For each element in arr[], find all the elements that are divisible by it and store them in a dictionary dic2
  • Now for each element in arr[], check if it is present in dic1
    • If yes, then remove it from dic1 and call the function func() recursively with the new dic1 and dic2
    • In the called function the passed array will be the elements stored in dic2.
    • The function will be called recursively until the dic1 becomes empty. At this point, we have found all the possible combinations of numbers that can be formed using the given array. 
  • Print the count of such combinations. 

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
int ans = 0;
 
// 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 list of factors of the number
void func(unordered_map<int, bool>& dic1,
          unordered_map<int, vector<int> >& dic2,
          vector<int>& q, int p)
{
    // For each element find the values which will be in the
    // same subset
    for (auto i : q) {
        if (dic1[i]) {
            dic1[i] = false;
 
            // Because in other cases those values are being
            // transitively searched and they belong to the
            // same subset as the first found element for
            // which p was 0.
            if (p == 0) {
                ans += 1;
            }
            auto k = dic2[i];
            // Repeat the same procedure for the values that
            // are non co-prime with i. As those elements
            // will also be a part of the same subset.
            func(dic1, dic2, k, p + 1);
        }
    }
}
// Function to find the maximum number of subsets
int maxSubset(vector<int> arr, int n)
{
    unordered_map<int, bool> dic1;
    unordered_map<int, vector<int> > dic2;
    for (auto i : arr) {
        dic1[i] = true;
    }
    for (auto i : arr) {
        vector<int> r;
        for (auto j : arr) {
            if (i != j && gcd(i, j) != 1) {
                r.push_back(j);
            }
        }
        dic2[i] = r;
    }
    func(dic1, dic2, arr, 0);
    return ans;
}
// Driver Code
int main()
{
    vector<int> arr{ 2, 3, 4, 5, 6 };
    int N = arr.size();
    cout << maxSubset(arr, N);
    return 0;
}
 
// This code is contributed by Tapesh (tapeshuda420)

Python3




# Python3 code to implement the approach
 
ans = 0
 
# Function to return gcd of a and b
def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)
   
# Function to find list of factors of the number
def func(dic1, dic2, q, p):
     
    # For each element find the values
    # which will be in the same subset
    for i in q:
        if dic1[i]:
            dic1[i] = False
             
            # Because in other cases those values
            # are being transitively searched
            # and they belong to the same subset
            # as the first found element
            # for which p was 0
            if p == 0:
                global ans
                ans += 1
            k = dic2[i]
             
            # Repeat the same procedure
            # for the values that are
            # non co-prime with i
            # As those elements will also be \
            # a part of the same subset
            func(dic1, dic2, k, p + 1)
 
# Function to find the maximum number of subsets
def maxSubset(arr, n):
    dic1 = {}
    dic2 = {}
    for i in range(n):
        dic1[arr[i]] = True
    for i in range(n):
        r = []
        for j in range(n):
            if i != j and gcd(arr[i], arr[j]) != 1:
                r.append(arr[j])
        dic2[arr[i]] = r
    func(dic1, dic2, arr, 0)
    return ans
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 4, 5, 6]
    N = len(arr)
     
    # Function call
    print(maxSubset(arr, N))

Output

2

Time Complexity: O(N2 * logM) where M is the maximum element of the array 
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!