# Powers of two and subsequences in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of N integers. Our task is to find the count of subsequences that can be formed such that if their elements are multiplied, they result in a number which is a power of two.

Let’s take an example to understand the problem,

Input − arr = [2, 5, 4]

Output − 3

Explanation − subsequences [2], [4] and [2, 4] give the desired result.

To solve this problem, we need to understand the logic of power.

Only those numbers with are powers of 2 will multiply to give the desired result. So, we have to consider only those subsequences from the array that itself are some powers of 2.

So, if in the array there are M elements that are powers of 2, then the count of sub-arrays will be 2M - 1

## Example

The program to show the implementation of our solution

Live Demo

#include <iostream>
#include <math.h>
using namespace std;
bool isPowerTwo(int num) {
if (num == 0)
return false;
if (num == 1)
return true;
if (num & (num - 1))
return false;
return true;
}
int SubsequenceWithPowerTwo(int arr[], int N) {
int count = 0;
for (int i = 0; i < N; i++)
if (isPowerTwo(arr[i]))
count++;
return (int)(pow(2, count)) - 1;
}
int main() {
int arr[] = {5, 4, 8, 12, 32, 9 };
int N = sizeof(arr)/sizeof(arr[0]);
cout<<"No. of subsequences which multiply to a number which is a power of 2 are : ";
cout<<SubsequenceWithPowerTwo(arr, N)<<endl;
return 0;
}

## Output

No. of subsequences which multiply to a number which is a power of 2 are : 7
Published on 17-Apr-2020 06:39:35