Count pairs with Bitwise-AND as even number 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 AND operation on the pairs will result in an even number.

The truth table for AND operation is given below

ABA^B
000
100
010
111

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

Output − Count of pairs with Bitwise AND as EVEN number are − 7

Explanation

a1a2a1^a2
250
210
280
290
511
580
591
180
191
898

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 AND operation as an even value.

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

  • Inside the loop, check IF arr[i] % 2 == FALSE then increment the count by 1

  • Set the count as count * (count - 1) / 2

  • Create a temporary variable to store the total number of pairs formed and set it to (size * (size - 1) / 2)

  • Store the odd number as subtracting count from total of pairs formed

  • Return the odd value

  • Print the result.

Example

 Live Demo

#include <iostream>
using namespace std;
//Count pairs with Bitwise AND as EVEN number
int count_pair(int arr[], int size){
   int count = 0;
   for (int i = 0; i < size; i++){
      if (arr[i] % 2 != 0){
         count++;
      }
   }
   count = count * (count - 1) / 2;
   int total_pair = (size * (size - 1) / 2);
   int odd = total_pair - count;
   return odd;
}
int main(){
   int arr[] = {2, 5, 1, 8, 3 };
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs with Bitwise-AND as even number are: "<<count_pair(arr, size) << endl;
   return 0;
}

Output

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

Count of pairs with Bitwise-AND as even number are: 7
raja
Published on 31-Aug-2020 09:15:10
Advertisements