Count pairs from given array with Bitwise OR equal to K
Given an array arr[] consisting of N positive integers and an integer K, the task is to count all pairs possible from the given array with Bitwise OR equal to K.
Examples:
Input: arr[] = {2, 38, 44, 29, 62}, K = 46
Output: 2
Explanation: Only the following two pairs are present in the array whose Bitwise OR is 46:
- 2 OR 44 = 46
- 38 OR 44 = 46
Input: arr[] = {1, 5, 20, 15, 14}, K = 20
Output: 5
Explanation:
There are only 5 pairs whose Bitwise OR is 20:
- 1 OR 15 = 15
- 1 OR 14 = 15
- 5 OR 15 = 15
- 5 OR 14 = 15
- 15 OR 14 = 15
Approach: To solve the problem, the idea is to generate all possible pairs from the given array and count those pairs whose Bitwise OR is equal to K. After checking for all the pairs, print the count stored.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void countPairs( int arr[], int k, int size)
{
int count = 0, x;
for ( int i = 0; i < size - 1; i++) {
for ( int j = i + 1; j < size; j++) {
x = arr[i] | arr[j];
if (x == k)
count++;
}
}
cout << count;
}
int main()
{
int arr[] = { 2, 38, 44, 29, 62 };
int K = 46;
int N = sizeof (arr) / sizeof (arr[0]);
countPairs(arr, K, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static void countPairs( int [] arr, int k,
int size)
{
int count = 0 , x;
for ( int i = 0 ; i < size - 1 ; i++)
{
for ( int j = i + 1 ; j < size; j++)
{
x = arr[i] | arr[j];
if (x == k)
count++;
}
}
System.out.println(count);
}
public static void main(String[] args)
{
int [] arr = { 2 , 38 , 44 , 29 , 62 };
int K = 46 ;
int N = arr.length;
countPairs(arr, K, N);
}
}
|
Python3
def countPairs(arr, k, size):
count = 0
for i in range (size - 1 ):
for j in range (i + 1 , size):
x = arr[i] | arr[j]
if (x = = k):
count + = 1
print (count)
arr = [ 2 , 38 , 44 , 29 , 62 ]
K = 46
N = len (arr)
countPairs(arr, K, N)
|
C#
using System;
class GFG{
static void countPairs( int [] arr, int k,
int size)
{
int count = 0, x;
for ( int i = 0; i < size - 1; i++)
{
for ( int j = i + 1; j < size; j++)
{
x = arr[i] | arr[j];
if (x == k)
count++;
}
}
Console.WriteLine(count);
}
public static void Main()
{
int [] arr = { 2, 38, 44, 29, 62 };
int K = 46;
int N = arr.Length;
countPairs(arr, K, N);
}
}
|
Javascript
<script>
function countPairs(arr, k, size)
{
let count = 0, x;
for (let i = 0; i < size - 1; i++)
{
for (let j = i + 1; j < size; j++)
{
x = arr[i] | arr[j];
if (x == k)
count++;
}
}
document.write(count);
}
let arr = [ 2, 38, 44, 29, 62 ];
let K = 46;
let N = arr.length;
countPairs(arr, K, N);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Last Updated :
28 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...