# Count subsets having distinct even numbers in C++

C++Server Side ProgrammingProgramming

We are given an array of positive integers. The goal is to find the subsets of numbers in an array such that each subset has distinct even numbers in it. All sets with the same elements will be counted as 1. [2,4,6] and [6,2,4] are the same set.

Let us understand with examples

Input − arr[] = {1,3,5,7,8,3,2 };

Output −Count of subsets having distinct even numbers are − 3

Explanation − Subsets will be − [2], [8], [2,8]

Input − arr[] = {2,4,6 };

Output −Count of subsets having distinct even numbers are − 7

Explanation − Subsets will be − [2], [4], [6], [2,4], [2,6], [4,6], [2,4,6]

## The approach used in the below program is as follows

We make a set of all even numbers in the array. This gives a count of distinct even numbers. The formula will be 2even count - 1

• Take an array of numbers arr[].

• Functionsubset_even(int arr[], int size) takes an array of numbers and returns the subsets with distinct even numbers.

• Take the initial count as 0.

• Create an unordered_set<int> un_set for even numbers.

• Traverse arr[] using for loop. From i=0 to i<length.

• If arr[i]%2==0, it is even. Insert to un_set.

• Take count=un_set.size() // distinct even numbers.

• Update count=pow(2,count) - 1.

• Return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int subset_even(int arr[], int size){
int count = 0;
unordered_set<int> un_set;
for(int i=0; i<size; i++){
if (arr[i] % 2 == 0){
un_set.insert(arr[i]);
}
}
unordered_set<int>:: iterator i;
count = un_set.size();
count = pow(2, count) - 1;
return count;
}
int main(){
int arr[] = {10, 4, 21, 3, 5, 7, 6, 8};
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of subsets having distinct even numbers are: "<<subset_even(arr, size);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of subsets having distinct even numbers are: 15
Published on 01-Dec-2020 12:15:31