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.
Input: X = 6
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
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:
Time complexity: O(log(X))
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count of pairs from Array with sum equal to twice their bitwise AND
- Count pairs with bitwise OR less than Max
- Count pairs with Bitwise XOR as ODD number
- Count pairs with Bitwise OR as Even number
- Count pairs with Bitwise-AND as even number
- Count pairs with Bitwise XOR as EVEN number
- Count of pairs whose bitwise AND is a power of 2
- Count pairs with Bitwise AND as ODD number
- Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
- Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs
- Count pairs from two arrays having sum equal to K
- Count pairs with set bits sum equal to K
- Count all distinct pairs with product equal to K
- Generate an array of given size with equal count and sum of odd and even numbers
- Count pairs in an array such that both elements has equal set bits
- Count of pairs of integers whose difference of squares is equal to N
- Count of pairs upto N such whose LCM is not equal to their product for Q queries
- Count pairs of natural numbers with GCD equal to given number
- Count the pairs in an array such that the difference between them and their indices is equal
- Count of pairs in a given range with sum of their product and sum equal to their concatenated number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.