![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
Output
2
Time Complexity: O(N2 * logM) where M is the maximum element of the array
Auxiliary Space: O(N)