Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count Subsets whose product is not divisible by perfect square
Next article icon

Count of subsets whose product is multiple of unique primes

Last Updated : 15 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 <bits/stdc++.h> 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<int>& subset,            vector<int>& 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<int> currSubset,                vector<int>& unique,                map<int, int>& 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<int>& arr, int N) {     // Initialize unique     set<int> uniqueSet;     for (int element : arr) {         // Check it is a product of distinct primes         if (checkDistinctPrime(element)) {             uniqueSet.insert(element);         }     }      vector<int> unique(uniqueSet.begin(), uniqueSet.end());      // Count frequency of unique element     map<int, int> frequency;     for (int element : unique) {         frequency[element]             = count(arr.begin(), arr.end(), element);     }      // Function Call     int ans         = countPrime(0, vector<int>(), unique, frequency);     return ans; }  // Driver Code int main() {     // Given Input     vector<int> 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<Integer> subset,                          List<Integer> 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<Integer> currSubset, List<Integer> unique, Map<Integer, Integer> 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<Integer> arr, int N)     {         // Initialize unique         Set<Integer> uniqueSet = new HashSet<Integer>();         for (int element : arr) {             // Check it is a product of distinct primes             if (checkDistinctPrime(element)) {                 uniqueSet.add(element);             }         }         List<Integer> unique= new ArrayList<Integer>(uniqueSet);         // Count frequency of unique element         Map<Integer, Integer> frequency = new HashMap<Integer, Integer>();         for (int element : unique) {             frequency.put(element, Collections.frequency(arr, element));         }         // Function Call         int ans = countPrime(0, new ArrayList<Integer>(),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<Integer> arr = new ArrayList<Integer>();         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<int> subset,                       List<int> 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<int> currSubset,                            List<int> unique, Dictionary<int, int> 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<int> arr, int N)     {              // Initialize unique       HashSet<int> uniqueSet = new HashSet<int>();       foreach (int element in arr)       {                  // Check it is a product of distinct primes         if (checkDistinctPrime(element))         {           uniqueSet.Add(element);         }       }       List<int> unique = new List<int>(uniqueSet);              // Count frequency of unique element       Dictionary<int, int> frequency = new Dictionary<int, int>();       foreach (int element in unique)       {         frequency.Add(element, arr.FindAll(x => x == element).Count);       }              // Function Call       int ans = countPrime(0, new List<int>(), 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<int> arr = new List<int>();       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
<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 whether 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)


Next Article
Count Subsets whose product is not divisible by perfect square

H

harshitkap00r
Improve
Article Tags :
  • Greedy
  • Recursion
  • DSA
  • Arrays
  • subset
  • prime-factor
  • Prime Number
Practice Tags :
  • Arrays
  • Greedy
  • Prime Number
  • Recursion
  • subset

Similar Reads

  • Product of Primes of all Subsets
    Given an array a[] of size N. The value of a subset is the product of primes in that subset. A non-prime is considered to be 1 while finding value by-product. The task is to find the product of the value of all possible subsets. Examples: Input: a[] = {3, 7} Output: 20 The subsets are: {3} {7} {3, 7
    8 min read
  • Count Subsets whose product is not divisible by perfect square
    Given an array arr[] (where arr[i] lies in the range [2, 30] )of size N, the task is to find the number of subsets such that the product of the elements is not divisible by any perfect square number. Examples: Input: arr[] = {2, 4, 3}Output : 3Explanation: Subset1 - {2} Subset2 - {3}Subset3 - {2, 3}
    8 min read
  • Product of unique prime factors of a number
    Given a number n, we need to find the product of all of its unique prime factors. Prime factors: It is basically a factor of the number that is a prime number itself. Examples : Input: num = 10 Output: Product is 10 Explanation: Here, the input number is 10 having only 2 prime factors and they are 5
    11 min read
  • Sum of the products of all possible Subsets
    Given an array of n non-negative integers. The task is to find the sum of the product of elements of all the possible subsets. It may be assumed that the numbers in subsets are small and computing product doesn't cause arithmetic overflow. Example : Input : arr[] = {1, 2, 3} Output : 23 Possible Sub
    4 min read
  • Count of all subsequence whose product is a Composite number
    Given an array arr[], the task is to find the number of non-empty subsequences from the given array such that the product of subsequence is a composite number.Example: Input: arr[] = {2, 3, 4} Output: 5 Explanation: There are 5 subsequences whose product is composite number {4}, {2, 3}, {2, 4}, {3,
    6 min read
  • Find the row whose product has maximum count of prime factors
    Given a matrix of size N x M, the task is to print the elements of the row whose product has a maximum count of prime factors.Examples: Input: arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; Output: 7 8 9 Explanation: Row 1: (1, 2, 3) has product 6 and it has 2 prime factors. Row 2: (4, 5, 6) has produ
    11 min read
  • Count of triplets till N whose product is at most N
    Given a positive integer N, the task is to find the number of triplets (A, B, C) from the first N Natural Numbers such that A * B * C ≤ N. Examples: Input: N = 2Output: 4Explanation:Following are the triplets that satisfy the given criteria: ( 1, 1, 1 ) => 1 * 1 * 1 = 1 ≤ 2.( 1, 1, 2 ) => 1 *
    9 min read
  • Count of subsequences of Array with last digit of product as K
    Given an array A[] of size N and a digit K. Find the number of sub-sequences of the array where the last digit of the product of the elements of the sub-sequence is K. Example: Input: A = {2, 3, 4, 2}, K = 2Output: 4Explanation: sub-sequences with product's last digit = 2 are: {2}, {2}, {2, 3, 2}, {
    12 min read
  • Counting Subsets with prime product property
    Given an array arr[] of size N. The task is to find a number of subsets whose product can be represented as a product of one or more distinct prime numbers. Modify your answer to the modulo of 109 + 7. Example: Input: N = 4, arr[] = {1, 2, 3, 4}Output: 6Explanation: The good subsets are: [1, 2]: pro
    11 min read
  • Count of Pairs such that modulo of product of one with their XOR and X is 1
    Given two arrays A[] and B[] of length N and M respectively and a prime number X, the task is to find the number of ordered pair of indices (i, j) that satisfies the following conditions: 1 ? i ? N and 1 ? j ? M( Ai ? Bj ) < X(( Ai ? ( Ai ? Bj )) ? 1) % X = 0 Note: ? is XOR operator. Examples: In
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences