Finding the total number of set-bits from 1 to n
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
In the realm of computer science and programming, you often need to work with binary representations of numbers. One common problem is determining the total number of set bits (1s) in the binary representation of the numbers from 1 to n
. This calculation has practical significance, particularly in applications relating to digital data processing, cryptography, and error detection algorithms. In this article, we explore methods and algorithms to efficiently determine the total number of set-bits from 1 to n
.
Understanding Set Bits
In binary numbers, a "set bit" refers to a bit that has a value of 1. For instance, the binary representation of the decimal number 5 is 101
, which has two set bits. The task involves calculating the total number of such set bits for all numbers from 1 to n
.
Simple Approach
Iterative Method
A straightforward approach to solve this is to iterate through each number from 1 to n
and count the set bits individually using a bit manipulation technique. A commonly used method is the "Brian Kernighan's Algorithm", which iterates through the binary representation of a number, turning off the rightmost set bit one by one. This is done using the expression n = n & (n - 1)
, and each iteration counts as one set bit.
Example
Consider the task of finding total set bits from 1 to 4:
- Binary of 1 is
0001• Set bits = 1 - Binary of 2 is
0010• Set bits = 1 - Binary of 3 is
0011• Set bits = 2 - Binary of 4 is
0100• Set bits = 1
Total set bits = 1 + 1 + 2 + 1 = 5.
Algorithm
• Bit 0: Full cycles: 2, Contributions: 2 full cycles x = 2 Remainder: 1 (contributes 1) • Bit 1: Full cycles: 1, Contributions: 1 full cycle x = 2 Remainder: 0 (no contribution) • Bit 2: Full cycles: 0, Contributions: 0 Remainder: 3 (contributes 0)
Related reading
- finding the width of a binary tree
- Finding three elements in an array whose sum is closest to a given number
- Finding two non-subsequent elements in array which sum is minimal
- Finding unique numbers from sorted array in less than On
- Finding translation and scale on two sets of points to get least square error in their distance?
- First occurrence in a binary search
- Finding unreachable sections of a 2D map
- Finding whether a point lies inside a rectangle or not

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.