You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/algebra/bit-manipulation.md
+38Lines changed: 38 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -186,6 +186,44 @@ int countSetBits(int n)
186
186
}
187
187
```
188
188
189
+
### Count set bits upto $n$
190
+
To count the number of set bits of all numbers upto the number $n$ (inclusive), we can run the Brian Kernighan's algorithm on all numbers upto $n$. But this will result in a "Time Limit Exceeded" in contest submissions.
191
+
192
+
We can use the fact that for numbers upto $2^x$ (i.e. from $1$ to $2^x - 1$) there are $x \cdot 2^{x-1}$ set bits. This can be visualised as follows.
193
+
```
194
+
0 -> 0 0 0 0
195
+
1 -> 0 0 0 1
196
+
2 -> 0 0 1 0
197
+
3 -> 0 0 1 1
198
+
4 -> 0 1 0 0
199
+
5 -> 0 1 0 1
200
+
6 -> 0 1 1 0
201
+
7 -> 0 1 1 1
202
+
8 -> 1 0 0 0
203
+
```
204
+
205
+
We can see that the all the columns except the leftmost have $4$ (i.e. $2^2$) set bits each, i.e. upto the number $2^3 - 1$, the number of set bits is $3 \cdot 2^{3-1}$.
206
+
207
+
With the new knowledge in hand we can come up with the following algorithm:
208
+
209
+
- Find the highest power of $2$ that is lesser than or equal to the given number. Let this number be $x$.
210
+
- Calculate the number of set bits from $1$ to $2^x - 1$ by using the formua $x \cdot 2^{x-1}$.
211
+
- Count the no. of set bits in the most significant bit from $2^x$ to $n$ and add it.
212
+
- Subtract $2^x$ from $n$ and repeat the above steps using the new $n$.
0 commit comments