Count total set bits in all numbers from 1 to n | Set 2
Last Updated :
18 Nov, 2021
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 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.
- Calculation for A (20 = 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;
}
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
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
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
JavaScript
<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>
Time Complexity: O(log n)
Auxiliary Space: O(1)
Similar Reads
Count total unset bits in all the numbers from 1 to N Given a positive integer N, the task is to count the total number of unset bits in the binary representation of all the numbers from 1 to N. Note that leading zeroes will not be counted as unset bits.Examples: Input: N = 5 Output: 4 IntegerBinary RepresentationCount of unset bits11021013110410025101
4 min read
Count total set bits in all numbers from range L to R Given two positive integers L and R, the task is to count the total number of set bits in the binary representation of all the numbers from L to R. Examples: Input: L = 3, R = 5 Output: 5 Explanation: (3)10 = (11)2, (4)10 = (100)2, (5)10 = (101)2 So, Total set bit in range 3 to 5 is 5 Input: L = 10,
15+ min read
Count total set bits in first N Natural Numbers (all numbers from 1 to N) Given a positive integer n, the task is to count the total number of set bits in binary representation of all natural numbers from 1 to n. Examples: Input: n= 3Output: 4Explanation: Numbers from 1 to 3: {1, 2, 3}Binary Representation of 1: 01 -> Set bits = 1Binary Representation of 2: 10 -> Se
9 min read
Count total bits in a number Given a positive number n, count total bit in it.Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 Method 1 (Using Log) The log2(n) logarithm in base 2 of n, which is the exponent to which 2 is raised to get n only integer and we add
7 min read
Python Bin | Count total bits in a number Given a positive number n, count total bit in it. Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 We have existing solution for this problem please refer Count total bits in a number link. Approach#1: We can solve this problem quick
3 min read
Count numbers up to N having Kth bit set Given two integers N and K, the task is to find the count of numbers up to N having K-th (0-based indexing) bit set. Examples: Input: N = 14, K = 2Output: 7Explanation: The numbers less than equal to 14, having 2nd bit set are 4, 5, 6, 7, 12, 13, and 14. Input: N = 6, K = 1Output: 3Explanation: The
5 min read