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
Added a new section "Count set bits upto n" under the Useful Tricks section after the Brian Kernighan's algorithm.
The Brian Kernighan's algorithm explains how to count the set bits of an integer n. The new added section explains how to count the set bits of all integers from 1 upto the number n, without giving a TLE during contest submissions.
The Solution was inspired by the following problem on geeksforgeeks:
https://www.geeksforgeeks.org/problems/count-total-set-bits-1587115620/1
Copy file name to clipboardExpand all lines: src/algebra/bit-manipulation.md
+53Lines changed: 53 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -186,6 +186,59 @@ 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*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*(2^{3-1})$.
206
+
207
+
With the new knowledge in hand we can come up with the following algorithm:
208
+
- Find the highest power of $2$ that is lesser than or equal to the given number. Let this number be $x$.
209
+
- Calculate the number of set bits from $1$ to $2^x - 1$ by using the formua $x*(2^{x-1})$.
210
+
211
+
The next steps needs more explanation.
212
+
- Count the no. of set bits in the most significant bit from $2^x$ to $n$ and add it.
213
+
- Subtract $2^x$ from $n$ and Recurse with the algorithm using the new $n$.
0 commit comments