Given two positive integers A and B such that A != B, the task is to find a positive integer X which maximizes the expression (A AND X) * (B AND X).
Input: A = 9 B = 8
(9 AND 8) * (8 AND 8) = 8 * 8 = 64 (maximum possible)
Input: A = 11 and B = 13
Naive approach: One can run a loop from 1 to max(A, B) and can easily find X which maximizes the given expression.
Efficient approach: It is known that,
(a – b)2 ≥ 0
which implies (a + b)2 – 4*a*b ≥ 0
which implies a * b ≤ (a + b)2 / 4
Hence, it concludes that a * b will be maximum when a * b = (a + b)2 / 4
which implies a = b
From the above result, (A AND X) * (B AND X) will be maximum when (A AND X) = (B AND X)
Now X can be found as:
A = 11 = 1011
B = 13 = 1101
X = ? = abcd
At 0th place: (1 AND d) = (1 AND d) implies d = 0, 1 but to maximize (A AND X) * (B AND X) d = 1
At 1st place: (1 AND d) = (0 AND d) implies c = 0
At 2nd place: (0 AND d) = (1 AND d) implies b = 0
At 3rd place: (1 AND d) = (1 AND d) implies a = 0, 1 but to maximize (A AND X) * (B AND X) a = 1
Hence, X = 1001 = 9
Below is the implementation of the above approach:
- Maximize the Expression | Bit Manipulation
- Maximize the value of the given expression
- Array Manipulation and Sum
- Bit manipulation | Swap Endianness of a number
- Bits manipulation (Important tactics)
- Winner in the Rock-Paper-Scissor game using Bit manipulation
- Expression Evaluation
- Maximize the value of x + y + z such that ax + by + cz = n
- Find all possible outcomes of a given expression
- Find Range Value of the Expression
- Find the minimum value of X for an expression
- What is an Expression and What are the types of Expressions?
- Maximize big when both big and small can be exchanged
- Maximize the number of subarrays with XOR as zero
- Maximize the bitwise OR of an array
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.