Sum of all subsets of a set formed by first n natural numbers
Given a number n, we need to find the sum of all the elements from all possible subsets of a set formed by first n natural numbers.
Examples :
Input : n = 2
Output : 6
Possible subsets are {{1}, {2},
{1, 2}}. Sum of elements in subsets
is 1 + 2 + 1 + 2 = 6
Input : n = 3
Output : 24
Possible subsets are {{1}, {2}, {3},
{1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}
Sum of subsets is :
1 + 2 + 3 + (1 + 2) + (1 + 3) +
(2 + 3) + (1 + 2 + 3)
A simple solution is to generate all subsets. For every subset, compute its sum and finally return overall sum.
An efficient solution is based on the fact that every number from 1 to n appears exactly 2(n-1) times. So our required sum is (1 + 2 + 3 + ..+ n) * 2(n-1). The sum can be written as (n * (n + 1)/2) * 2(n-1)
C++
#include <bits/stdc++.h>
using namespace std;
unsigned long long findSumSubsets( int n)
{
return (n * (n + 1) / 2) * (1 << (n - 1));
}
int main()
{
int n = 3;
cout << findSumSubsets(n);
return 0;
}
|
Java
class GFG {
static long findSumSubsets( int n)
{
return (n * (n + 1 ) / 2 ) * ( 1 << (n - 1 ));
}
public static void main(String[] args)
{
int n = 3 ;
System.out.print(findSumSubsets(n));
}
}
|
Python3
def findSumSubsets( n):
return (n * (n + 1 ) / 2 ) * ( 1 << (n - 1 ))
n = 3
print (findSumSubsets(n))
|
C#
using System;
class GFG {
static long findSumSubsets( int n)
{
return (n * (n + 1) / 2) * (1 << (n - 1));
}
public static void Main()
{
int n = 3;
Console.WriteLine(findSumSubsets(n));
}
}
|
PHP
<?php
function findSumSubsets( $n )
{
return ( $n * ( $n + 1) / 2) *
(1 << ( $n - 1));
}
$n = 3;
echo findSumSubsets( $n );
?>
|
Javascript
<script>
function findSumSubsets( n)
{
return (n * (n + 1) / 2) * (1 << (n - 1));
}
let n = 3;
document.write(findSumSubsets(n));
</script>
|
Output :
24
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
10 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...