I got this task:
You are given 5 integers a,b,c,d,k. Print the maximum value of x+y that follows the given conditions:
- a<=x<=b
- c<=y<=d
- x^y=k ('^' sign denotes XOR operation)
Constraints:
- 0 <= a <= b <= 10^18
- 0 <= c <= d <= 10^18
Explanation:
- x and y are the 2 numbers,
- k is their xor value ,
- [a,b] is range of x ,
- [c,d] is range of y.
My Attempt:
found=False
a,b,c,d,k=map(int,input().split())
for x in range(b,a,-1):
if found==True:
break
for y in range(d,c,-1):
if x^y ==k:
print(x+y)
found=True
break
I know its the brute force but this is the only algorithm I can think of to solve the problem but this is obviously not gonna work as the time complexity is O((b-a)*(d-c)) or in the worst case, it could take 10^36 operations. This approach needs to be optimized to logarithmic or constant time complexity.
Reading similar question from here,
X+Y = (X ^ Y) + 2 * (X & Y)
So,
ans = k + 2*(X&Y)
So, I need to find the maximum value of and operation of 2 numbers whose range is given. But how to do it?
Any help is appreciated, thanks.
10^18 is about 2^60 (a little smaller). You can work on the bits and only check numbers that would give a valid xor result. This is already a lot better than your algorithm, but I don't know if it is good enough.