Open In App

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:
 



Decimal Binary Set Bit Count
1 01 1
2 10 1
3 11 2

1 + 1 + 2 = 4
Input: N = 16 
Output: 33 
 

 



Recommended Practice

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, 
 

  1. Every alternate bits in A are set.
  2. Every 2 alternate bits in B are set.
  3. Every 4 alternate bits in C are set.
  4. Every 8 alternate bits in D are set.
  5. …..
  6. 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. 
 

Example: Consider N = 14 
From the table above, there will be 28 set bits in total from 1 to 14. 
We will be considering 20 as A, 21 as B, 22 as C and 23 as D
First of all we will add 1 to number N, So now our N = 14 + 1 = 15. 
 ^ represents raise to the power ,not XOR.

eg. 2^3 means 2 raise to 3.

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++ 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;
}




// 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




# 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




// 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




<script>
// javascript implementation of the approach// Function to return the sum of the count
// of set bits in the integers from 1 to n
function countSetBits(n)
{
 
    // Ignore 0 as all the bits are unset
    n++;
 
    // To store the powers of 2
    var 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
    var cnt = n / 2;
 
    // Loop for every bit required to represent n
    while (powerOf2 <= n)
    {
 
        // Total count of pairs of 0s and 1s
        var 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
var n = 14;
 
document.write(countSetBits(n));
 
// This code is contributed by 29AjayKumar
</script>

Output: 
28

 

Time Complexity: O(log n)

Auxiliary Space: O(1)


Article Tags :