Count of pairs having bit size at most X and Bitwise OR equal to X
Given a number X, calculate number of possible pairs (a, b) such that bitwise or of a and b is equal to X and number of bits in both a and b is less than equal to number of bits in X.
Examples:
Input: X = 6
Output: 9
Explanation:
The possible pairs of (a, b) are (4, 6), (6, 4), (6, 6), (6, 2), (4, 2), (6, 0), (2, 6), (2, 4), (0, 6).
Input: X = 21
Output: 27
Explanation:
In total there are 27 pairs possible.
Approach: To solve the problem mentioned above follow the steps given below:
- Iterate through every bit of given number X.
- If the bit is 1 then from the truth table of Bitwise OR we know that there are 3 combinations possible for that given bit in number a and b that is (0, 1), (1, 0), (1, 1) that is 3 possible ways.
- If the bit is 0 then from the truth table of Bitwise OR we know that there is only 1 combination possible for that given bit in number a and b that is (0, 0).
- So our answer will be answer will be 3 ^ (number of on bits in X).
Below is the implementation of above approach:
C++
#include <iostream>
using namespace std;
int count_pairs( int x)
{
int ans = 1;
while (x > 0) {
if (x % 2 == 1)
ans = ans * 3;
x = x / 2;
}
return ans;
}
int main()
{
int X = 6;
cout << count_pairs(X)
<< endl;
return 0;
}
|
Java
class GFG{
static int count_pairs( int x)
{
int ans = 1 ;
while (x > 0 )
{
if (x % 2 == 1 )
ans = ans * 3 ;
x = x / 2 ;
}
return ans;
}
public static void main(String[] args)
{
int X = 6 ;
System.out.print(count_pairs(X) + "\n" );
}
}
|
Python3
def count_pairs(x):
ans = 1 ;
while (x > 0 ):
if (x % 2 = = 1 ):
ans = ans * 3 ;
x = x / / 2 ;
return ans;
if __name__ = = '__main__' :
X = 6 ;
print (count_pairs(X));
|
C#
using System;
class GFG{
static int count_pairs( int x)
{
int ans = 1;
while (x > 0)
{
if (x % 2 == 1)
ans = ans * 3;
x = x / 2;
}
return ans;
}
public static void Main(String[] args)
{
int X = 6;
Console.Write(count_pairs(X) + "\n" );
}
}
|
Javascript
<script>
function count_pairs(x) {
var ans = 1;
while (x > 0) {
if (x % 2 == 1)
ans = ans * 3;
x = parseInt(x / 2);
}
return ans;
}
var X = 6;
document.write(count_pairs(X) + "\n" );
</script>
|
Time complexity: O(log(X))
Auxiliary Space: O(1)
Last Updated :
16 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...