Reputation: 644
I want to find the number of subsets whose elements are divisible by 2 or whose sum of the elements is divisible by 2
I have found all the possible subset of the given array
for(int i=1;i<=(Math.pow(2,n));i++) //Loop for all 2^n combinations
{
for(int j=0;j<n;j++)
{
if((i&(1<<j))>0) //This gives the subset of the array
Input:1 2 3 Output: 3 as {2},{1,3=4},{1,2,3=6} are the subsets which are divisible by 2 or whose sum of the elements is divisible by 2.
Upvotes: 0
Views: 84
Reputation: 13299
Under the assumptions, that:
n
(a natural number)...the (exact) result is:
respectively (=):
respectively (=):
An O(log(n))
algorithm:
public class Test {
public static long countSuperClever(int n) {
return pow(2L, (long) n - 1) - 1L;
}
// best thx to https://codingforspeed.com/using-faster-integer-power-in-java/
private static long pow(long a, long b) {
long re = 1L;
while (b > 0) {
if ((b & 1) == 1) {
re *= a;
}
b >>= 1;
a *= a;
}
return re;
}
public static void main(String[] args) {
for (int i = 3; i < 12; i++) {
System.out.println(countSuperClever(i));
}
}
}
See also: https://math.stackexchange.com/a/1338830/20447
Upvotes: 1