Sum of cubes of all Subsets of given Array
Given an array
arr[]
, the task is to calculate the sum of cubes of all possible non-empty subsets of the given array. Since, the answer can be large, print the value as
mod
1000000007.
Examples:
Input: arr[] = {1, 2} Output: 18 subset({1}) = 13 = 1 subsetval({2}) = 23 = 8 subset({1, 2}) = 13 + 23 = 1 + 8 = 9 Sum of cubes of all Subsets = 1 + 8 + 9 = 18 Input: arr[] = {1, 1, 1} Output: 12
Naive approach:
A simple approach is to
find all the subset
and then cube each element in that subset and add it to the result. The time complexity of this approach will be
O(2
N
)
Efficient approach:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long power( int p)
{
long long res = 1;
for ( int i = 1; i <= p; ++i) {
res *= 2;
res %= mod;
}
return res % mod;
}
long long subset_cube_sum(vector< int >& A)
{
int n = ( int )A.size();
long long ans = 0;
for ( int i : A) {
ans += (1LL * i * i * i) % mod;
ans %= mod;
}
return (1LL * ans * power(n - 1))
% mod;
}
int main()
{
vector< int > A = { 1, 2 };
cout << subset_cube_sum(A);
return 0;
}
|
Java
public class GFG {
static final long MOD = ( long ) 1e9 + 7 ;
static long power( int p) {
long res = 1 ;
for ( int i = 1 ; i <= p; i++) {
res *= 2 ;
res %= MOD;
}
return res % MOD;
}
static long subsetCubeSum( int [] A) {
int n = A.length;
long ans = 0 ;
for ( int i : A) {
ans += (i * i * i) % MOD;
ans %= MOD;
}
return (ans * power(n - 1 )) % MOD;
}
public static void main(String[] args) {
int [] A = { 1 , 2 };
System.out.println(subsetCubeSum(A));
}
}
|
Python3
mod = int ( 1e9 ) + 7 ;
def power(p) :
res = 1 ;
for i in range ( 1 , p + 1 ) :
res * = 2 ;
res % = mod;
return res % mod;
def subset_cube_sum(A) :
n = len (A);
ans = 0 ;
for i in A :
ans + = (i * i * i) % mod;
ans % = mod;
return (ans * power(n - 1 )) % mod;
if __name__ = = "__main__" :
A = [ 1 , 2 ];
print (subset_cube_sum(A));
|
C#
using System;
public class GFG {
static readonly long MOD = ( long )1e9 + 7;
static long Power( int p) {
long res = 1;
for ( int i = 1; i <= p; i++) {
res = (res * 2) % MOD;
}
return res;
}
static long SubsetCubeSum( int [] A) {
int n = A.Length;
long ans = 0;
foreach ( int i in A) {
ans = (ans + ((i * i * i) % MOD)) % MOD;
}
return (ans * Power(n - 1)) % MOD;
}
public static void Main( string [] args) {
int [] A = { 1, 2 };
Console.WriteLine(SubsetCubeSum(A));
}
}
|
Javascript
const mod = BigInt(1e9 + 7);
function power(p) {
let res = BigInt(1);
for (let i = 1; i <= p; ++i) {
res *= BigInt(2);
res %= mod;
}
return res;
}
function subsetCubeSum(A) {
const n = A.length;
let ans = BigInt(0);
for (let i of A) {
ans += (BigInt(i) * BigInt(i) * BigInt(i)) % mod;
ans %= mod;
}
return (ans * power(n - 1)) % mod;
}
const A = [1, 2];
console.log(subsetCubeSum(A).toString());
|
Time Complexity:
O(N)
Last Updated :
09 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...