Given l and r, find the number of pairs of natural numbers from l to r which Bitwise AND is equal to 0.
Limits :
1 <= l <= r <= 10^9
r - l <= 10^6
I could only write a brute force. Does anyone have an idea how to solve this task? The range size is upto 10^6, so we could use that somehow.
First write the following function:
You can write that with your point about the bits - you just find the biggest nonzero bits that can work staying in range, remove the bits that MUST be 0, and you have the base 2 representation of one less than the number of ands that meet the condition. (The counting trick missed
0.)And now we use the following fact. Suppose that
x & y == 0. Then:(2*x) & (2*y) == 0(2*x + 1) & (2*y) == 0(2*x) & (2*y + 1) == 0But
(2*x + 1) & (2*y + 1) == 1.So we can pair up most of the range from
ltor, drop the bottom bit fromlandrto get a smaller range, count the ands of the range, and then multiply by 3. We also have to be careful with the boundaries. So we get something like this:This will be only 20 recursive calls to a trivial range. So it should be quite fast.