Skip to content
Related Articles

Related Articles

Improve Article

Count of subsets whose product is multiple of unique primes

  • Difficulty Level : Expert
  • Last Updated : 09 Jul, 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.


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: 


# 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)
        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 = 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)

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

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :