Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Count of subsets whose product is multiple of unique primes

  • Difficulty Level : Expert
  • Last Updated : 05 Oct, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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: 

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 wheather 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)

Javascript




<script>
    // Javascript program for the above approach
     
    // Function to return
    // gcd of a and b
    function gcd(a, b)
    {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }
 
    // Function to check number has
    // distinct prime
    function checkDistinctPrime(n)
    {
        let original = n;
        let product = 1;
 
        // While N has factors of
        // two
        if (n % 2 == 0)
        {
            product *= 2;
            while (n % 2 == 0)
            {
                n = parseInt(n/2, 10);
            }
        }
 
        // Traversing till sqrt(N)
        for(let i = 3; i < parseInt(Math.sqrt(n), 10); 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 = parseInt(n / i, 10);
                }
            }
        }
 
        // Covering case, N is Prime
        if (n > 2)
        {
            product = product * n;
        }
 
        return product == original;
    }
 
    // Function to check wheather num
    // can be added to the subset
    function check(pos, subset, unique)
    {
        for(let num = 0; num < subset.length; num++)
        {
            if(gcd(subset[num], unique[pos]) != 1)
            {
                return false;
            }
        }
        return true;
    }
 
    // Recursive Function to count subset
    function countPrime(pos, currSubset, unique, frequency)
    {
        // Base Case
        if(pos == unique.length)
        {
            // If currSubset is empty
            if(currSubset.length == 0)
                return 0;
 
            count = 1;
            for(let element = 0; element < currSubset.length; element++)
            {
                count *= frequency[currSubset[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
    function countSubsets(arr, N)
    {
        // Initialize unique
        let unique = new Set();
        for(let element = 0; element < arr.length; element++)
        {
            return 5;
            // Check it is a product of
            // distinct primes
            if(checkDistinctPrime(element))
            {
                unique.add(element);
            }
        }
 
        unique = Array.from(unique);
 
        // Count frequency of unique element
        let frequency = new Map();
        for(let element = 0; element < unique.length; element++)
        {
            let freq = 0;
            for(let i = 0; i < unique.length; i++)
            {
                if(unique[element] == unique[i])
                {
                    freq++;
                }
            }
            frequency[element] = freq;
        }
 
        // Function Call
        let ans = countPrime(0, [], unique, frequency);
        return ans;
    }
     
    // Given Input
    let arr = [2, 4, 7, 10];
    let N = arr.length;
       
    // Function Call
    let ans = countSubsets(arr, N);
    document.write(ans);
     
    // This code is contributed by divyesh072019.
</script>
Output
5

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :