can anyone help me to crack any formula or code rather than O(n) to count the sum of number of set bits in upto Nth
N Bit
Ex: 1 -> 1
2 -> 1 + 1 (this 1 is previous one as we are summing those)
3 -> 4
4 -> 5
5 -> 7
|
|
Nth term formula???
I tried to crack the pattern like:
for first bit 2^0: 1 and 0 makes pattern of 01010101---------Nth
for second bit 2^1: 1 and 0 makes pattern of 00110011---------Nth
for third bit 2^2: 1 and 0 makes pattern of 00001111---------Nth
Let's look for dependencies. Results for
0001111**(kones) patterns arek*2^(k-1), so result for patterns containing the onle one "1" (2^k) is1 + k*2^(k-1). So we can separate the most significant one bit (MSB), get count for numbers upto corresponding power of two, then add both count for right tail value and that right tail value itself (because of MSB). Python code:Addition:
Why numbers upto
kones givek*2^(k-1)bits:Consider k-bits values from 0000 to 1111. There are 2^k of them. Every bit is "0" in the half of values, and is "1", so we can count
2^(k-1)ones for every bit number, and multiply bykfor allkbits.Why check bits from left to right?
If we have binary value
1110, we can count ones for values in range0000...1000as above, then add count of ones in range1001..1110. The last range contains110b=6decvalues, so we have to account for 6 one bits at the left, and count ones in001..110range and so on.