set-bits
counting-bits
binary-representation
algorithm
programming-tutorial

Finding the total number of set-bits from 1 to n

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

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:

  1. Binary of 1 is 0001 • Set bits = 1
  2. Binary of 2 is 0010 • Set bits = 1
  3. Binary of 3 is 0011 • Set bits = 2
  4. 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 202^{0} = 2 Remainder: 1 (contributes 1) • Bit 1: Full cycles: 1, Contributions: 1 full cycle x 212^{1} = 2 Remainder: 0 (no contribution) • Bit 2: Full cycles: 0, Contributions: 0 Remainder: 3 (contributes 0)


Course illustration
Course illustration

All Rights Reserved.