Count subsets that satisfy the given condition in C++


Given an array of numbers and an integer x as input. The goal is to find all the subsets of arr[] such that individual elements of that set as well as the sum of them fully divisible by x.

For Example

Input

arr[] = {1,2,3,4,5,6} x=3

Output

Count of subsets that satisfy the given condition :3

Explanation

The subsets will be:
[3], [6], [3,6]

Input

arr[] = {1,2,3,4,5,6} x=4

Output

Count of subsets that satisfy the given condition :1

Explanation

The subsets will be:
[4]

Approach used in the below program is as follows

In this approach we will count the elements of arr[] that are fully divisible by x and then return 2count−1 as required number of subsets.

  • Take an integer array arr[].

  • Take x as input.

  • Function count(int arr[], int n, int x) takes an array and x and returns count of subsets that satisfy the given condition.

  • If x is 1 then it divides all elements, so return

Example

 Live Demo

#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int sub_sets(int arr[], int size, int val){
int count = 0;
if (val == 1){
   count = pow(2, size) − 1;
      return count;
   }
   for (int i = 0; i < size; i++){
      if (arr[i] % val == 0){
         count++;
      }
   }
   count = pow(2, count) − 1;
   return count;
}
int main(){
   int arr[] = { 4, 6, 1, 3, 8, 10, 12 }, val = 4;
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of sub−sets that satisfy the given condition are: "<<sub_sets(arr, size, val);
   return 0;
}

Output

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

Count of sub−sets that satisfy the given condition are: 7

Updated on: 05-Jan-2021

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements