How can I count "1" digits in binary representation of a numbers from a to b.
Where 0 < a <= b < 10^16.
How can I count "1" digits in binary representation of a numbers from a to b.
Where 0 < a <= b < 10^16.
To find solution of the task P[a..b], you have to find solutions for subproblems P[0..b] and P[0..a] and subtract these values.
Now consider P[0..x] task. Simple case x=2^k (100..000bin).
0th bit is set in 2^k/2 numbers (it alternates every time)
1th bit is set in 2^k/2 numbers (it alternates after pair of numbers)
..
k-1th bit is set in 2^k/2 numbers (in 2^(k-1)..(2^k)-1))
kth bit is set in one number (in 2^k)
So
P[0..2^k] = k * 2^(k-1) + 1
To find solution for arbitrary x, we can exploit binary representation of x, for example:
P(1010b) = P(1000b) + P(10b)
pseudocode
P = 0
k = 0
while x <> 0 do
if (x and 1) then //check if kth bit is set in x
P = P + k * 2^(k-1) + 1
x = x >> 1 //shift right
k = k + 1