Sum of all subsets of a set formed by first n natural numbers


A Set is a collection of data elements. Subset of a set is a set formed by only the elements after parent set. for example, B is A subset of a if all elements of B exist in A.

Here we need to find the sum of all subsets of a set found by first n natural numbers. this means I need to find all subsets that can be formed and then adding them. Let's take an example,

N = 3

Set = {1,2,3}

subsets formed = { {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3,} }

Sum = 1+1+2+1+3+2+2+3+3+1+2+3 = 24

Lets rearrange the sum, 1+1+1+1+2+2+2+2+3+3+3 = 4(1+2+3) = 24

There exists a mathematical formula for this type of series, General formula of the series is 2^n*(n^2 + n + 2) – 1.

Example

#include <stdio.h>
#define mod (int)(1e9 + 7)
int power(int x, int y) {
   int res = 1;
   x = x % mod;
   while (y > 0) {
      if (y & 1)
         res = (res * x) % mod;
         y = y >> 1;
         x = (x * x) % mod;
   }
   return res;
}
int main() {
   int n = 45;
   n--;
   int ans = n * n;
   if (ans >= mod)
      ans %= mod;
      ans += n + 2;
   if (ans >= mod)
      ans %= mod;
      ans = (power(2, n) % mod * ans % mod) % mod;
      ans = (ans - 1 + mod) % mod;
   printf("The sum of the series is %d 
", ans);    return 0; }

Output

The sim of the series is 2815

Updated on: 19-Aug-2019

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements