GFG App
Open App
Browser
Continue

# Count of subsets whose product is multiple of unique primes

Given an array arr[] of size N,  the task is to count the number of non-empty subsets whose product is equal to P1×P2×P3×……..×Pk  where P1, P2, P3, …….Pk are distinct prime numbers.

Examples:

Input: arr[ ] = {2, 4, 7, 10}
Output: 5
Explanation: There are a total of 5 subsets whose product is the product of distinct primes.
Subset 1: {2} -> 2
Subset 2: {2, 7} -> 2×7
Subset 3: {7} -> 7
Subset 4: {7, 10} -> 2×5×7
Subset 5: {10} -> 2×5

Input: arr[ ] = {12, 9}
Output: 0

Approach: The main idea is to find the numbers which are products of only distinct primes and call the recursion either to include them in the subset or not include in the subset. Also, an element is only added to the subset if and only if the GCD of the whole subset after adding the element is 1. Follow the steps below to solve the problem:

• Initialize a dict, say, Freq, to store the frequency of array elements.
• Initialize an array, say, Unique[] and store all those elements which are products of only distinct primes.
• Call a recursive function, say Countprime(pos, curSubset) to count all those subsets.
• Base Case: if pos equals the size of the unique array:
• if curSubset is empty, then return 0
• else, return the product of frequencies of each element of curSubset.
• Check if the element at pos can be taken in the current subset or not
• If taken, then call recursive functions as the sum of countPrime(pos+1, curSubset) and countPrime(pos+1, curSubset+[unique[pos]]).
• else, call countPrime(pos+1, curSubset).
• Print the ans returned from the function.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach   #include using namespace std;   // Function to check number has distinct prime bool checkDistinctPrime(int n) {     int original = n;     int product = 1;       // While N has factors of two     if (n % 2 == 0) {         product *= 2;         while (n % 2 == 0) {             n /= 2;         }     }       // Traversing till sqrt(N)     for (int i = 3; i <= sqrt(n); i += 2) {         // If N has a factor of i         if (n % i == 0) {             product = product * i;               // While N has a factor of i             while (n % i == 0) {                 n /= i;             }         }     }       // Covering case, N is Prime     if (n > 2) {         product = product * n;     }       return product == original; }   // Function to check whether num can be added to the subset bool check(int pos, vector& subset,            vector& unique) {     for (int num : subset) {         if (__gcd(num, unique[pos]) != 1) {             return false;         }     }     return true; }   // Recursive Function to count subset int countPrime(int pos, vector currSubset,                vector& unique,                map& frequency) {     // Base Case     if (pos == unique.size()) {         // If currSubset is empty         if (currSubset.empty()) {             return 0;         }           int count = 1;         for (int element : currSubset) {             count *= frequency[element];         }         return count;     }       int ans = 0;     // If Unique[pos] can be added to the Subset     if (check(pos, currSubset, unique)) {         ans += countPrime(pos + 1, currSubset, unique,                           frequency);         currSubset.push_back(unique[pos]);         ans += countPrime(pos + 1, currSubset, unique,                           frequency);     }     else {         ans += countPrime(pos + 1, currSubset, unique,                           frequency);     }     return ans; }   // Function to count the subsets int countSubsets(vector& arr, int N) {     // Initialize unique     set uniqueSet;     for (int element : arr) {         // Check it is a product of distinct primes         if (checkDistinctPrime(element)) {             uniqueSet.insert(element);         }     }       vector unique(uniqueSet.begin(), uniqueSet.end());       // Count frequency of unique element     map frequency;     for (int element : unique) {         frequency[element]             = count(arr.begin(), arr.end(), element);     }       // Function Call     int ans         = countPrime(0, vector(), unique, frequency);     return ans; }   // Driver Code int main() {     // Given Input     vector arr = { 2, 4, 7, 10 };     int N = arr.size();       // Function Call     int ans = countSubsets(arr, N);     cout << ans << endl;       return 0; }

## Java

 // Java program for the above approach import java.util.*; class Main {     // Function to check number has distinct prime     static boolean checkDistinctPrime(int n)     {         int original = n;         int product = 1;         // While N has factors of two         if (n % 2 == 0) {             product *= 2;             while (n % 2 == 0) {                 n /= 2;             }         }         // Traversing till sqrt(N)         for (int i = 3; i <= Math.sqrt(n); i += 2) {             // If N has a factor of i             if (n % i == 0) {                 product = product * i;                 // While N has a factor of i                 while (n % i == 0) {                     n /= i;                 }             }         }         // Covering case, N is Prime         if (n > 2) {             product = product * n;         }         return product == original;     }     // Function to check whether num can be added to the subset     static boolean check(int pos, List subset,                          List unique)     {         for (int num : subset) {             if (gcd(num, unique.get(pos)) != 1) {                 return false;             }         }         return true;     }     // Recursive Function to count subset     static int countPrime(int pos, List currSubset, List unique, Map frequency)     {         // Base Case         if (pos == unique.size()) {             // If currSubset is empty             if (currSubset.isEmpty()) {                 return 0;             }             int count = 1;             for (int element : currSubset) {                 count *= frequency.get(element);             }             return count;         }         int ans = 0;         // If Unique[pos] can be added to the Subset         if (check(pos, currSubset, unique)) {             ans += countPrime(pos + 1, currSubset, unique,frequency);             currSubset.add(unique.get(pos));             ans += countPrime(pos + 1, currSubset, unique,frequency);             currSubset.remove(currSubset.size() - 1);         }         else {             ans += countPrime(pos + 1, currSubset, unique,frequency);         }         return ans;     }     // Function to count the subsets     static int countSubsets(List arr, int N)     {         // Initialize unique         Set uniqueSet = new HashSet();         for (int element : arr) {             // Check it is a product of distinct primes             if (checkDistinctPrime(element)) {                 uniqueSet.add(element);             }         }         List unique= new ArrayList(uniqueSet);         // Count frequency of unique element         Map frequency = new HashMap();         for (int element : unique) {             frequency.put(element, Collections.frequency(arr, element));         }         // Function Call         int ans = countPrime(0, new ArrayList(),unique, frequency);         return ans;     }      // Recursive function to return gcd of a and b     static int gcd(int a, int b)     {       if (b == 0)         return a;       return gcd(b, a % b);     }     // Driver Code     public static void main(String[] args)     {         // Given Input         List arr = new ArrayList();         arr.add(2);         arr.add(4);         arr.add(7);         arr.add(10);         int N = arr.size();         // Function Call         int ans = countSubsets(arr, N);         System.out.println(ans);     } }

## Python3

 # Python program for the above approach   # Importing the module from math import gcd, sqrt   # Function to check number has # distinct prime def checkDistinctPrime(n):     original = n     product = 1       # While N has factors of     # two     if (n % 2 == 0):         product *= 2         while (n % 2 == 0):             n = n//2           # Traversing till sqrt(N)     for i in range(3, int(sqrt(n)), 2):                 # If N has a factor of i         if (n % i == 0):             product = product * i                           # While N has a factor             # of i             while (n % i == 0):                 n = n//i       # Covering case, N is Prime     if (n > 2):         product = product * n       return product == original     # Function to check whether num # can be added to the subset def check(pos, subset, unique):     for num in subset:         if gcd(num, unique[pos]) != 1:             return False     return True     # Recursive Function to count subset def countPrime(pos, currSubset, unique, frequency):       # Base Case     if pos == len(unique):                   # If currSubset is empty         if not currSubset:             return 0           count = 1         for element in currSubset:             count *= frequency[element]         return count       # If Unique[pos] can be added to     # the Subset     if check(pos, currSubset, unique):         return countPrime(pos + 1, currSubset, \                           unique, frequency)\              + countPrime(pos + 1, currSubset+[unique[pos]], \                           unique, frequency)     else:         return countPrime(pos + 1, currSubset, \                           unique, frequency)     # Function to count the subsets def countSubsets(arr, N):         # Initialize unique     unique = set()     for element in arr:         # Check it is a product of         # distinct primes         if checkDistinctPrime(element):             unique.add(element)       unique = list(unique)           # Count frequency of unique element     frequency = dict()     for element in unique:         frequency[element] = arr.count(element)       # Function Call     ans = countPrime(0, [], unique, frequency)     return ans   # Driver Code if __name__ == "__main__":       # Given Input     arr = [2, 4, 7, 10]     N = len(arr)           # Function Call     ans = countSubsets(arr, N)     print(ans)

## C#

 // C# equivalent code using System; using System.Collections.Generic;   namespace CSharpProgram {   class MainClass   {           // Function to check number has distinct prime     static bool checkDistinctPrime(int n)     {       int original = n;       int product = 1;               // While N has factors of two       if (n % 2 == 0)       {         product *= 2;         while (n % 2 == 0)         {           n /= 2;         }       }               // Traversing till sqrt(N)       for (int i = 3; i <= Math.Sqrt(n); i += 2)       {                   // If N has a factor of i         if (n % i == 0)         {           product = product * i;                       // While N has a factor of i           while (n % i == 0)           {             n /= i;           }         }       }               // Covering case, N is Prime       if (n > 2)       {         product = product * n;       }       return product == original;     }           // Function to check whether num can be added to the subset     static bool check(int pos, List subset,                       List unique)     {       foreach (int num in subset)       {         if (gcd(num, unique[pos]) != 1)         {           return false;         }       }       return true;     }           // Recursive Function to count subset     static int countPrime(int pos, List currSubset,                           List unique, Dictionary frequency)     {               // Base Case       if (pos == unique.Count)       {                   // If currSubset is empty         if (currSubset.Count == 0)         {           return 0;         }         int count = 1;         foreach (int element in currSubset)         {           count *= frequency[element];         }         return count;       }       int ans = 0;               // If Unique[pos] can be added to the Subset       if (check(pos, currSubset, unique))       {         ans += countPrime(pos + 1, currSubset, unique, frequency);         currSubset.Add(unique[pos]);         ans += countPrime(pos + 1, currSubset, unique, frequency);         currSubset.RemoveAt(currSubset.Count - 1);       }       else       {         ans += countPrime(pos + 1, currSubset, unique, frequency);       }       return ans;     }           // Function to count the subsets     static int countSubsets(List arr, int N)     {               // Initialize unique       HashSet uniqueSet = new HashSet();       foreach (int element in arr)       {                   // Check it is a product of distinct primes         if (checkDistinctPrime(element))         {           uniqueSet.Add(element);         }       }       List unique = new List(uniqueSet);               // Count frequency of unique element       Dictionary frequency = new Dictionary();       foreach (int element in unique)       {         frequency.Add(element, arr.FindAll(x => x == element).Count);       }               // Function Call       int ans = countPrime(0, new List(), unique, frequency);       return ans;     }           // Recursive function to return gcd of a and b     static int gcd(int a, int b)     {       if (b == 0)         return a;       return gcd(b, a % b);     }           // Driver Code     public static void Main(string[] args)     {               // Given Input       List arr = new List();       arr.Add(2);       arr.Add(4);       arr.Add(7);       arr.Add(10);       int N = arr.Count;               // Function Call       int ans = countSubsets(arr, N);       Console.WriteLine(ans);     }   } }

## Javascript



Output

5

Time Complexity: O(2N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up