
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sum of Sum of All Subsequences 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 −
Subset | Sum |
---|---|
5 | 5 |
6 | 6 |
8 | 8 |
5,6 | 11 |
6,8 | 14 |
5,8 | 13 |
5,6,8 | 19 |
Total Sum | 76 |
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
#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
Advertisements