Sum of the products of all possible Subsets in C++


In this problem, we are given an array arr[] of N numbers. Our task is to create a program that will find the sum of the products of all possible subsets.

Here, we will find all subsets and then find the product of all elements for each subset. Then add all the values to calculate the sum.

Let’s take an example to understand the problem,

Input

arr[] = {4, 5, 6}

Output

209

Explanation −

All subsets of arr[] are: {4}, {5}, {6}, {4, 5}, {5, 6}, {4, 6}, {4, 5, 6}
Sum of product
= (4) + (5) + (6) + (4*5) + (5*6) + (4*6) + (4*5*6)
= (4) + (5) + (6) + (20) + (30) + (24) + (120)
= 209

A simple approach to solve the problem is to find all the subsets of the set and calculator the product of elements of each set. And add all the products, the return all final sum after all the subsets are traversed.

Example

Program to illustrate the working of our solution,

 Live Demo

#include<iostream>
#include<math.h>
using namespace std;
int findSumProductSubset(int *arr, int set_length) {
   unsigned int size = pow(2, set_length);
   int sum = 0;
   int product;
   for(int counter = 1; counter < size; counter++) {
      product = 1;
      for(int j = 0; j < size; j++) {
         if(counter & (1<<j))
         product *= arr[j];
      }
      sum += product;
   }
   return sum;
}
int main() {
   int arr[] = {4, 5, 6};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"The sum of the product of all subsets is "<<findSumProductSubset(arr, n);
}

Output

The sum of the product of all subsets is 209

The above approach generates all the subsets hence has exponential time complexity. Hence, it is not the most efficient approach.

A more efficient approach would be find a pattern for the solution.

Now, Let’s see a set of three numbers x, y, z.

sum = x + y + z + xy + yz + xz + xyz

sum = x + xz + y + yz + xy + xyz + z + 1 - 1

sum = x(1+z) + y(1+z) + xy(1+z) + 1(z+1) - 1

sum = ( x + y + xy + 1 )( 1 + z ) - 1

sum = ( x(1 + y) + 1(1+y) )(1+z) - 1

sum = (1 + x) * (1 + y) * (1 + z) - 1

This can be genralised in the following way,

For n element set,

sum = (1+ e1) * (1 + e2) * … * (1 + en) - 1

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int productOfSubsetSums(int arr[], int n) {
   int sum = 1;
   for (int i = 0; i < n; ++i )
   sum *= (arr[i] + 1);
   sum --;
   return sum;
}
int main() {
   int arr[] = {5, 6, 8 , 9};
   int n = sizeof(arr)/sizeof arr[0];
   cout<<"Sum of product of all possible subsets is "<<productOfSubsetSums(arr, n);
   return 0;
}

Output

Sum of product of all possible subsets is 3779

Updated on: 14-Aug-2020

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements