Skip to content
Related Articles

Related Articles

Improve Article

Product of Primes of all Subsets

  • Last Updated : 18 May, 2021

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} 
{3, 7} = 3 * 7 = 21 
{3} = 3 
{7} = 7 
21 * 3 * 7 = 441 
Input: a[] = {10, 2, 14, 3} 
Output: 1679616

 

Naive Approach: A naive approach is to find all the subsets using power set and then find the product by multiplying all the values of the subset. Prime can be checked using Sieve
Time Complexity: O(2N)
Efficient Approach: An efficient approach is to solve the problem using observation. If we write all the subsequences, a common point of observation is that each number appears 2(N – 1) times in a subset and hence will lead to the 2(N-1) as the contribution to the product. Iterate through the array and check if the element in the array is prime or not. If it prime, then its contribution is arr[i]2(N-1) times to the answer. 
Below is the implementation of the above approach: 
 

C++




// C++ program to find the product of
// the multiplication of
// prime numbers in all possible subsets.
#include <bits/stdc++.h>
using namespace std;
 
// Sieve method to check prime or not
void sieve(int n, vector<bool>& prime)
{
    // Initially mark all primes
    for (int i = 2; i <= n; i++)
        prime[i] = true;
    prime[0] = prime[1] = false;
 
    // Iterate and mark all the
    // non primes as false
    for (int i = 2; i <= n; i++) {
        if (prime[i]) {
            // Multiples of prime marked as false
            for (int j = i * i; j <= n; j += i) {
                prime[j] = false;
            }
        }
    }
}
 
// Function to find the sum
// of sum of all the subset
int sumOfSubset(int a[], int n)
{
 
    // Get the maximum element
    int maxi = *max_element(a, a + n);
 
    // Declare a sieve array
    vector<bool> prime(maxi + 1);
 
    // Sieve function called
    sieve(maxi, prime);
 
    // Number of times an element
    // contributes to the answer
    int times = pow(2, n - 1);
 
    int sum = 1;
 
    // Iterate and check
    for (int i = 0; i < n; i++) {
        // If prime
        if (prime[a[i]])
        sum = sum * (pow(a[i], times)); // Contribution
    }
 
    return sum;
}
 
// Driver Code
int main()
{
    int a[] = { 3, 7 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << sumOfSubset(a, n);
}

Java




// Java program to find the product of
// the multiplication of
// prime numbers in all possible subsets.
import java.util.*;
 
class GFG
{
 
// Sieve method to check prime or not
static void sieve(int n, boolean []prime)
{
    // Initially mark all primes
    for (int i = 2; i <= n; i++)
        prime[i] = true;
    prime[0] = prime[1] = false;
 
    // Iterate and mark all the
    // non primes as false
    for (int i = 2; i <= n; i++)
    {
        if (prime[i])
        {
            // Multiples of prime marked as false
            for (int j = i * i; j <= n; j += i)
            {
                prime[j] = false;
            }
        }
    }
}
 
// Function to find the sum
// of sum of all the subset
static int sumOfSubset(int a[], int n)
{
 
    // Get the maximum element
    int maxi = Arrays.stream(a).max().getAsInt();
 
    // Declare a sieve array
    boolean []prime = new boolean[maxi + 1];
 
    // Sieve function called
    sieve(maxi, prime);
 
    // Number of times an element
    // contributes to the answer
    int times = (int) Math.pow(2, n - 1);
 
    int sum = 1;
 
    // Iterate and check
    for (int i = 0; i < n; i++)
    {
        // If prime
        if (prime[a[i]])
        sum = (int) (sum * (Math.pow(a[i], times)));
    }
 
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = { 3, 7 };
    int n = a.length;
    System.out.println(sumOfSubset(a, n));
}
}
 
// This code is contributed by Rajput-Ji

Python3




# Python3 program to find the product of
# the multiplication of
# prime numbers in all possible subsets.
prime = [True for i in range(100)]
 
# Sieve method to check prime or not
def sieve(n, prime):
     
    # Initially mark all primes
    for i in range(1, n + 1):
        prime[i] = True
    prime[0] = prime[1] = False
 
    # Iterate and mark all the
    # non primes as false
    for i in range(2, n + 1):
        if (prime[i]):
             
            # Multiples of prime marked as false
            for j in range(2 * i, n + 1, i):
                prime[j] = False
 
# Function to find the Sum
# of Sum of all the subset
def SumOfSubset(a, n):
 
    # Get the maximum element
    maxi = max(a)
 
    # Declare a sieve array
 
    # Sieve function called
    sieve(maxi, prime)
 
    # Number of times an element
    # contributes to the answer
    times = pow(2, n - 1)
 
    Sum = 1
 
    # Iterate and check
    for i in range(n):
         
        # If prime
        if (prime[a[i]]):
            Sum = Sum * (pow(a[i], times)) # Contribution
 
    return Sum
 
# Driver Code
a = [3, 7]
n = len(a)
print(SumOfSubset(a, n))
 
# This code is contributed
# by Mohit Kumar

C#




// C# program to find the product of
// the multiplication of
// prime numbers in all possible subsets.
using System;
using System.Linq;
 
class GFG
{
 
// Sieve method to check prime or not
static void sieve(int n, Boolean []prime)
{
    // Initially mark all primes
    for (int i = 2; i <= n; i++)
        prime[i] = true;
    prime[0] = prime[1] = false;
 
    // Iterate and mark all the
    // non primes as false
    for (int i = 2; i <= n; i++)
    {
        if (prime[i])
        {
            // Multiples of prime marked as false
            for (int j = i * i; j <= n; j += i)
            {
                prime[j] = false;
            }
        }
    }
}
 
// Function to find the sum
// of sum of all the subset
static int sumOfSubset(int []a, int n)
{
 
    // Get the maximum element
    int maxi = a.Max();
 
    // Declare a sieve array
    Boolean []prime = new Boolean[maxi + 1];
 
    // Sieve function called
    sieve(maxi, prime);
 
    // Number of times an element
    // contributes to the answer
    int times = (int) Math.Pow(2, n - 1);
 
    int sum = 1;
 
    // Iterate and check
    for (int i = 0; i < n; i++)
    {
        // If prime
        if (prime[a[i]])
        sum = (int) (sum * (Math.Pow(a[i], times)));
    }
    return sum;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []a = { 3, 7 };
    int n = a.Length;
    Console.WriteLine(sumOfSubset(a, n));
}
}
 
// This code is contributed by PrinciRaj1992

Javascript




<script>
// javascript program to find the product of
// the multiplication of
// prime numbers in all possible subsets.
 
    // Sieve method to check prime or not
    function sieve(n,  prime)
    {
     
        // Initially mark all primes
        for (var i = 2; i <= n; i++)
            prime[i] = true;
        prime[0] = prime[1] = false;
 
        // Iterate and mark all the
        // non primes as false
        for (i = 2; i <= n; i++)
        {
            if (prime[i])
            {
             
                // Multiples of prime marked as false
                for (j = i * i; j <= n; j += i) {
                    prime[j] = false;
                }
            }
        }
    }
 
    // Function to find the sum
    // of sum of all the subset
    function sumOfSubset(a , n) {
 
        // Get the maximum element
        var maxi = Math.max.apply(Math,a);
 
        // Declare a sieve array
        var prime =Array(maxi + 1).fill(0);
 
        // Sieve function called
        sieve(maxi, prime);
 
        // Number of times an element
        // contributes to the answer
        var times = parseInt( Math.pow(2, n - 1));
 
        var sum = 1;
 
        // Iterate and check
        for (i = 0; i < n; i++) {
            // If prime
            if (prime[a[i]])
                sum = parseInt( (sum * (Math.pow(a[i], times))));
        }
 
        return sum;
    }
 
    // Driver Code
        var a = [ 3, 7 ];
        var n = a.length;
        document.write(sumOfSubset(a, n));
 
// This code is contributed by umadevi9616
</script>
Output: 



441

 

Time Complexity: O(M log M) for pre calculation where M is the maximum element and O(N) for iteration. 
Space Complexity: O(M)
Note: As arr[i]2(N-1) can be really big, the answer can overflow, its preferable to use larger data-type and mod operations to conserve the answer.
 

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 :