Find sum of sum of all sub-sequences in C++


Consider we have an array A with n elements. We have to find the total sum of the sum of all the subsets of the array. So if the array is like A = [5, 6, 8], then it will be like −

SubsetSum
55
66
88
5,611
6,814
5,813
5,6,819
Total Sum76

As the array has n elements, then we have a 2n number of subsets (including empty). If we observe it clearly, then we can find that each element occurs 2n-1 times

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
int totalSum(int arr[], int n) {
   int res = 0;
   for (int i = 0; i < n; i++)
      res += arr[i];
   return res * pow(2, n - 1);
}
int main() {
   int arr[] = { 5, 6, 8 };
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Total sum of the sum of all subsets: " << totalSum(arr, n) << endl;
}

Output

Total sum of the sum of all subsets: 76

Updated on: 19-Dec-2019

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements