# Count total set bits in all numbers from 1 to n | Set 2

Given a positive integer **N**, the task is to count the sum of the number of set bits in the binary representation of all the numbers from **1** to **N**.

**Examples:**

Input:N = 3

Output:4

Decimal Binary Set Bit Count 1 01 1 2 10 1 3 11 2 1 + 1 + 2 = 4

Input:N = 16

Output:33

**Approach:** Some other approaches to solve this problem has been discussed here. In this article, another approach with time complexity O(logN) has been discussed.

Check the pattern of Binary representation of the numbers from 1 to N in the following table:

Decimal | E | D | C | B | A |
---|---|---|---|---|---|

0 | 0 | 0 | 0 | 0 | 0 |

1 | 0 | 0 | 0 | 0 | 1 |

2 | 0 | 0 | 0 | 1 | 0 |

3 | 0 | 0 | 0 | 1 | 1 |

4 | 0 | 0 | 1 | 0 | 0 |

5 | 0 | 0 | 1 | 0 | 1 |

6 | 0 | 0 | 1 | 1 | 0 |

7 | 0 | 0 | 1 | 1 | 1 |

8 | 0 | 1 | 0 | 0 | 0 |

9 | 0 | 1 | 0 | 0 | 1 |

10 | 0 | 1 | 0 | 1 | 0 |

11 | 0 | 1 | 0 | 1 | 1 |

12 | 0 | 1 | 1 | 0 | 0 |

13 | 0 | 1 | 1 | 0 | 1 |

14 | 0 | 1 | 1 | 1 | 0 |

15 | 0 | 1 | 1 | 1 | 1 |

16 | 1 | 0 | 0 | 0 | 0 |

Notice that,

- Every alternate bits in A are set.
- Every 2 alternate bits in B are set.
- Every 4 alternate bits in C are set.
- Every 8 alternate bits in D are set.
- …..
- This will keep on repeating for every power of 2.

So, we will iterate till the number of bits in the number. And we don’t have to iterate every single number in the range from 1 to n.

We will perform the following operations to get the desired result.

- , First of all, we will add 1 to the number in order to compensate 0. As the binary number system starts from 0. So now n = n + 1.
- We will keep the track of the number of set bits encountered till now. And we will initialise it with n/2.
- We will keep one variable which is a power of 2, in order to keep track of bit we are computing.
- We will iterate till the power of 2 becomes greater than n.
- We can get the number of pairs of 0s and 1s in the current bit for all the numbers by dividing n by current power of 2.
- Now we have to add the bits in the set bits count. We can do this by dividing the number of pairs of 0s and 1s by 2 which will give us the number of pairs of 1s only and after that, we will multiply that with the current power of 2 to get the count of ones in the groups.
- Now there may be a chance that we get a number as number of pairs, which is somewhere in the middle of the group i.e. the number of 1s are less than the current power of 2 in that particular group. So, we will find modulus and add that to the count of set bits which will be clear with the help of an example.

**Example:** Consider N = 14

From the table above, there will be 28 set bits in total from 1 to 14.

We will be considering 2^{0} as A, 2^{1} as B, 2^{2} as C and 2^{3} as D

First of all we will add 1 to number N, So now our N = 14 + 1 = 15.

- Calculation for A (2
^{0}= 1)

15/2 = 7

Number of set bits in A = 7 ————> (i) - Calculation for B (2^1 = 2)

15/2 = 7 => there are 7 groups of 0s and 1s

Now, to compute number of groups of set bits only, we have to divide that by 2.

So, 7/2 = 3. There are 3 set bit groups.

And these groups will contain set bits equal to power of 2 this time, which is 2. So we will multiply number of set bit groups with power of 2

=> 3*2 = 6 —>(2i)

Plus

There may be some extra 1s in this because 4th group is not considered, as this division will give us only integer value. So we have to add that as well. Note: – This will happen only when number of groups of 0s and 1s is odd.

15%2 = 1 —>(2ii)

2i + 2ii => 6 + 1 = 7 ————>(ii) - Calculation for C (2^2 = 4)

15/4 = 3 => there are 3 groups of 0s and 1s

Number of set bit groups = 3/2 = 1

Number of set bits in those groups = 1*4 = 4 —> (3i)

As 3 is odd, we have to add bits in the group which is not considered

So, 15%4 = 3 —> (3ii)

3i + 3ii = 4 + 3 = 7 ————>(iii) - Calculation for D (2^3 = 8)

15/8 = 1 => there is 1 group of 0s and 1s. Now in this case there is only one group and that too of only 0.

Number of set bit groups = 1/2 = 0

Number of set bits in those groups = 0 * 8 = 0 —> (4i)

As number of groups are odd,

So, 15%8 = 7 —> (4ii)

4i + 4ii = 0 + 7 = 7 ————>(iv)

At this point, our power of 2 variable becomes greater than the number, which is 15 in our case. (power of 2 = 16 and 16 > 15). So the loop gets terminated here.

Final output = i + ii + iii + iv = 7 + 7 + 7 + 7 = 28

Number of set bits from 1 to 14 are 28.

Below is the implementation of the above approach:

## C++

`// C++ implementation of the approach ` `#include <iostream> ` `using` `namespace` `std; ` ` ` `// Function to return the sum of the count ` `// of set bits in the integers from 1 to n ` `int` `countSetBits(` `int` `n) ` `{ ` ` ` ` ` `// Ignore 0 as all the bits are unset ` ` ` `n++; ` ` ` ` ` `// To store the powers of 2 ` ` ` `int` `powerOf2 = 2; ` ` ` ` ` `// To store the result, it is initialized ` ` ` `// with n/2 because the count of set ` ` ` `// least significant bits in the integers ` ` ` `// from 1 to n is n/2 ` ` ` `int` `cnt = n / 2; ` ` ` ` ` `// Loop for every bit required to represent n ` ` ` `while` `(powerOf2 <= n) { ` ` ` ` ` `// Total count of pairs of 0s and 1s ` ` ` `int` `totalPairs = n / powerOf2; ` ` ` ` ` `// totalPairs/2 gives the complete ` ` ` `// count of the pairs of 1s ` ` ` `// Multiplying it with the current power ` ` ` `// of 2 will give the count of ` ` ` `// 1s in the current bit ` ` ` `cnt += (totalPairs / 2) * powerOf2; ` ` ` ` ` `// If the count of pairs was odd then ` ` ` `// add the remaining 1s which could ` ` ` `// not be groupped together ` ` ` `cnt += (totalPairs & 1) ? (n % powerOf2) : 0; ` ` ` ` ` `// Next power of 2 ` ` ` `powerOf2 <<= 1; ` ` ` `} ` ` ` ` ` `// Return the result ` ` ` `return` `cnt; ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `int` `n = 14; ` ` ` ` ` `cout << countSetBits(n); ` ` ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

## Java

`// Java implementation of the approach ` `class` `GFG ` `{ ` ` ` `// Function to return the sum of the count ` `// of set bits in the integers from 1 to n ` `static` `int` `countSetBits(` `int` `n) ` `{ ` ` ` ` ` `// Ignore 0 as all the bits are unset ` ` ` `n++; ` ` ` ` ` `// To store the powers of 2 ` ` ` `int` `powerOf2 = ` `2` `; ` ` ` ` ` `// To store the result, it is initialized ` ` ` `// with n/2 because the count of set ` ` ` `// least significant bits in the integers ` ` ` `// from 1 to n is n/2 ` ` ` `int` `cnt = n / ` `2` `; ` ` ` ` ` `// Loop for every bit required to represent n ` ` ` `while` `(powerOf2 <= n) ` ` ` `{ ` ` ` ` ` `// Total count of pairs of 0s and 1s ` ` ` `int` `totalPairs = n / powerOf2; ` ` ` ` ` `// totalPairs/2 gives the complete ` ` ` `// count of the pairs of 1s ` ` ` `// Multiplying it with the current power ` ` ` `// of 2 will give the count of ` ` ` `// 1s in the current bit ` ` ` `cnt += (totalPairs / ` `2` `) * powerOf2; ` ` ` ` ` `// If the count of pairs was odd then ` ` ` `// add the remaining 1s which could ` ` ` `// not be groupped together ` ` ` `cnt += (totalPairs % ` `2` `== ` `1` `) ? ` ` ` `(n % powerOf2) : ` `0` `; ` ` ` ` ` `// Next power of 2 ` ` ` `powerOf2 <<= ` `1` `; ` ` ` `} ` ` ` ` ` `// Return the result ` ` ` `return` `cnt; ` `} ` ` ` `// Driver code ` `public` `static` `void` `main(String[] args) ` `{ ` ` ` `int` `n = ` `14` `; ` ` ` ` ` `System.out.println(countSetBits(n)); ` `} ` `} ` ` ` `// This code is contributed by Princi Singh ` |

*chevron_right*

*filter_none*

## Python3

`# Python3 implementation of the approach ` ` ` `# Function to return the sum of the count ` `# of set bits in the integers from 1 to n ` `def` `countSetBits(n) : ` ` ` ` ` `# Ignore 0 as all the bits are unset ` ` ` `n ` `+` `=` `1` `; ` ` ` ` ` `# To store the powers of 2 ` ` ` `powerOf2 ` `=` `2` `; ` ` ` ` ` `# To store the result, it is initialized ` ` ` `# with n/2 because the count of set ` ` ` `# least significant bits in the integers ` ` ` `# from 1 to n is n/2 ` ` ` `cnt ` `=` `n ` `/` `/` `2` `; ` ` ` ` ` `# Loop for every bit required to represent n ` ` ` `while` `(powerOf2 <` `=` `n) : ` ` ` ` ` `# Total count of pairs of 0s and 1s ` ` ` `totalPairs ` `=` `n ` `/` `/` `powerOf2; ` ` ` ` ` `# totalPairs/2 gives the complete ` ` ` `# count of the pairs of 1s ` ` ` `# Multiplying it with the current power ` ` ` `# of 2 will give the count of ` ` ` `# 1s in the current bit ` ` ` `cnt ` `+` `=` `(totalPairs ` `/` `/` `2` `) ` `*` `powerOf2; ` ` ` ` ` `# If the count of pairs was odd then ` ` ` `# add the remaining 1s which could ` ` ` `# not be groupped together ` ` ` `if` `(totalPairs & ` `1` `) : ` ` ` `cnt ` `+` `=` `(n ` `%` `powerOf2) ` ` ` `else` `: ` ` ` `cnt ` `+` `=` `0` ` ` ` ` `# Next power of 2 ` ` ` `powerOf2 <<` `=` `1` `; ` ` ` ` ` `# Return the result ` ` ` `return` `cnt; ` ` ` `# Driver code ` `if` `__name__ ` `=` `=` `"__main__"` `: ` ` ` ` ` `n ` `=` `14` `; ` ` ` ` ` `print` `(countSetBits(n)); ` ` ` `# This code is contributed by AnkitRai01 ` |

*chevron_right*

*filter_none*

## C#

`// C# implementation of the approach ` `using` `System; ` ` ` `class` `GFG ` `{ ` ` ` `// Function to return the sum of the count ` `// of set bits in the integers from 1 to n ` `static` `int` `countSetBits(` `int` `n) ` `{ ` ` ` ` ` `// Ignore 0 as all the bits are unset ` ` ` `n++; ` ` ` ` ` `// To store the powers of 2 ` ` ` `int` `powerOf2 = 2; ` ` ` ` ` `// To store the result, it is initialized ` ` ` `// with n/2 because the count of set ` ` ` `// least significant bits in the integers ` ` ` `// from 1 to n is n/2 ` ` ` `int` `cnt = n / 2; ` ` ` ` ` `// Loop for every bit required to represent n ` ` ` `while` `(powerOf2 <= n) ` ` ` `{ ` ` ` ` ` `// Total count of pairs of 0s and 1s ` ` ` `int` `totalPairs = n / powerOf2; ` ` ` ` ` `// totalPairs/2 gives the complete ` ` ` `// count of the pairs of 1s ` ` ` `// Multiplying it with the current power ` ` ` `// of 2 will give the count of ` ` ` `// 1s in the current bit ` ` ` `cnt += (totalPairs / 2) * powerOf2; ` ` ` ` ` `// If the count of pairs was odd then ` ` ` `// add the remaining 1s which could ` ` ` `// not be groupped together ` ` ` `cnt += (totalPairs % 2 == 1) ? ` ` ` `(n % powerOf2) : 0; ` ` ` ` ` `// Next power of 2 ` ` ` `powerOf2 <<= 1; ` ` ` `} ` ` ` ` ` `// Return the result ` ` ` `return` `cnt; ` `} ` ` ` `// Driver code ` `public` `static` `void` `Main(String[] args) ` `{ ` ` ` `int` `n = 14; ` ` ` ` ` `Console.WriteLine(countSetBits(n)); ` `} ` `} ` ` ` `// This code is contributed by 29AjayKumar ` |

*chevron_right*

*filter_none*

**Output:**

28

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

## Recommended Posts:

- Count total set bits in all numbers from 1 to n
- Count total set bits in all numbers from 1 to N | Set 3
- Count total unset bits in all the numbers from 1 to N
- Python map function | Count total set bits in all numbers from 1 to n
- Count total bits in a number
- Count of total subarrays whose sum is a Fibonacci Numbers
- Find the total count of numbers up to N digits in a given base B
- Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
- Count of numbers whose 0th and Nth bits are set
- Count set bits in the Kth number after segregating even and odd from N natural numbers
- Check if bits of a number has count of consecutive set bits in increasing order
- Total distinct pairs from two arrays such that second number can be obtained by inverting bits of first
- Total character pairs from two strings, with equal number of set bits in their ascii value
- Print numbers having first and last bits as the only set bits
- Total no of 1's in numbers

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.