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}
{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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
  
    // Seive 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);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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];
  
    // Seive 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
  
    # Seive 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

chevron_right


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]; // Seive 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 [tabbyending]

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.



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.