# Count pairs with bitwise OR less than Max in C++

C++Server Side ProgrammingProgramming

We are given an integer array and the task is to count the total number of pairs that can be formed using the given array values such that the OR operation on the pairs will result in the value less than MAX value in the given pair.

The truth table for OR operation is given below

 A B AVB 0 0 0 1 0 1 0 1 1 1 1 1

Input − int arr[] = {2, 5, 1, 8, 9}

Output − Count of pairs with bitwise OR less than Max are − 3

Explanation

 X Y X V Y 2 5 7>5=FALSE 2 1 3>2=FALSE 2 8 10>8=FALSE 2 9 11>9=FALSE 5 1 5=5 TRUE 5 8 13>8=FALSE 5 9 13>9=FALSE 1 8 9>8=FALSE 1 9 10>9=FALSE 8 9 9=9= TRUE

## Approach used in the below program is as follows

• Input an array of integer elements to form an pair

• Calculate the size of an array pass the data to the function for further processing

• Create a temporary variable count to store the pairs formed with OR operation having value less than or equals to MAX value amongst the pair

• Start loop FOR from i to 0 till the size-1 of an array

• Inside the loop, start another loop FOR from j to i+1 till the size of an array

• Inside the loop, check IF arr[i] | arr[j] <= max(arr[i], arr[j]) then increment the count by 1

• Return the count

• Print the result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
//Count pairs with bitwise OR less than Max
int Pair_OR(int arr[], int size){
int count = 0;
for (int i = 0; i lt; size - 1; i++){
for (int j = i + 1; j lt; size; j++){
if ((arr[i] | arr[j]) lt;= max(arr[i], arr[j])){
count++;
}
}
}
return count;
}
int main(){
int arr[] = { 4, 8, 9, 10, 23};
int size = sizeof(arr) / sizeof(arr);
cout<<"Count of pairs with bitwise OR less than Max are: "<<Pair_OR(arr, size);
return 0;
}

## Output

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

Count of pairs with bitwise OR less than Max are − 3