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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read