Open In App

Count total set bits in first N Natural Numbers (all numbers from 1 to N)

Last Updated : 18 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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= 3
Output:  4
Explanation: Numbers from 1 to 3: {1, 2, 3}
Binary Representation of 1: 01 -> Set bits = 1
Binary Representation of 2: 10 -> Set bits = 1
Binary Representation of 3: 11 -> Set bits = 2
Total set bits from 1 till 3 = 1 + 1 + 2 = 4

Input: n = 6
Output: 9

Input: n= 7
Output: 12

[Naive Approach] Counting Bits for each number

The idea is to traverse all numbers from 1 to n and use an idea of count set bits to count in the individual numbers. Finally, return sum of all counts.

C++
// C++ program to Count set
// bits in an integer
#include <iostream>
using namespace std;

// Function to get no of set bits in binary
// representation of positive integer n
int setBits(int n) {
	int count = 0;
	while (n) {
		count += n & 1;
		n >>= 1;
	}
	return count;
}

// Count total set bits in all 
// numbers from 1 to n
int countSetBits(int n)  {
   int res = 0;
   for (int i=1; i<=n; i++)
      res += setBits(i);
   return res;
}

int main() {
	int i = 3;
	cout << countSetBits(i);
	return 0;
}
Java
// Java program to Count set
// bits in an integer

import java.util.*;

class GfG {

    // Function to get no of set bits in binary
    // representation of positive integer n
    static int setBits(int n) {
        int count = 0;
        while (n != 0) {
            count += n & 1;
            n >>= 1;
        }
        return count;
    }

    // Count total set bits in all 
    // numbers from 1 to n
    static int countSetBits(int n) {
        int res = 0;
        for (int i = 1; i <= n; i++)
            res += setBits(i);
        return res;
    }

    public static void main(String[] args) {
        int i = 3;
        System.out.println(countSetBits(i));
    }
}
Python
# Python program to Count set
# bits in an integer

# Function to get no of set bits in binary
# representation of positive integer n
def setBits(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

# Count total set bits in all 
# numbers from 1 to n
def countSetBits(n):
    res = 0
    for i in range(1, n + 1):
        res += setBits(i)
    return res

if __name__ == "__main__":
    i = 3
    print(countSetBits(i))
C#
// C# program to Count set
// bits in an integer

using System;

class GfG {

    // Function to get no of set bits in binary
    // representation of positive integer n
    static int setBits(int n) {
        int count = 0;
        while (n != 0) {
            count += n & 1;
            n >>= 1;
        }
        return count;
    }

    // Count total set bits in all 
    // numbers from 1 to n
    static int countSetBits(int n) {
        int res = 0;
        for (int i = 1; i <= n; i++)
            res += setBits(i);
        return res;
    }

    static void Main(string[] args) {
        int i = 3;
        Console.WriteLine(countSetBits(i));
    }
}
JavaScript
// JavaScript program to Count set
// bits in an integer

// Function to get no of set bits in binary
// representation of positive integer n
function setBits(n) {
    let count = 0;
    while (n !== 0) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

// Count total set bits in all 
// numbers from 1 to n
function countSetBits(n) {
    let res = 0;
    for (let i = 1; i <= n; i++)
        res += setBits(i);
    return res;
}

//Driver code
let i = 3;
console.log(countSetBits(i));

Output
4

Time Complexity: O(k*n), where k is the number of binary digits.
Auxiliary Space: O(1).

[Expected Approach] Using Pattern Based Approach - O(1) Time and O(1) Space

The idea is to calculate set bits at each position independently by recognising that bits follow a fixed pattern at each position - for any position i, bits alternate between 0s and 1s in groups of size 2^(i+1), where first half are 0s and second half are 1s. By calculating how many complete groups exist, and how many set bits are in each complete group, plus handling any remaining partial group's set bits, we can sum up total set bits at each position.

Step by step approach:

  1. Increment n by 1 (to find set bits between 0 and n).
  2. Initialise result to 0.
  3. For each bit position i from 0 to 29:
    • Find size of pattern at this position = 2^(i+1)
    • Count complete patterns in n = n/size
    • Each complete pattern contributes size/2 set bits. So add (size/2)*(complete groups) to result.
    • Find remaining numbers = n%size in the last group.
    • If the remaining group contains set bits, add them to result.
  4. Return the result.

Why set bits of n+1 numbers is calculated?

The reason we increment n by 1 (counting from 0 to N instead of 1 to N) is that binary patterns naturally align with powers of 2 starting from 0, making the pattern recognition and calculations simpler.

Illustration:

Taking example of n = 8.

Number -> 0 1 2 3 4 5 6 7 8

Position 0: 0 1 0 1 0 1 0 1 0 (size=2: groups of 01)

Position 1: 0 0 1 1 0 0 1 1 0 (size=4: groups of 0011)

Position 2: 0 0 0 0 1 1 1 1 0 (size=8: groups of 00001111)

Position 3: 0 0 0 0 0 0 0 0 1 (size=16: groups of 0000000011111111)

At i = 0:

  • size = 2^(0+1) = 2
  • Complete groups = 9/2 = 4 groups
  • Each group has: 2/2 = 1 set bit
  • Remaining numbers = 9%2 = 1 > size/2(1), so add (1-1) = 0 extra bits
  • Total = 4 * 1 + 0 = 4 bits

At i = 1:

  • size = 2^(1+1) = 4
  • Complete groups = 9/4 = 2 groups
  • Each group has: 4/2 = 2 set bits
  • Remaining numbers = 9%4 = 1 ≯ size/2(2), so add 0 extra bits
  • Total = 2 * 2 + 0 = 4 bits

At i = 2:

  • size = 2^(2+1) = 8
  • Complete groups = 9/8 = 1 group
  • Each group has: 8/2 = 4 set bits
  • Remaining numbers = 9%8 = 1 ≯ size/2(4), so add 0 extra bits
  • Total = 1 * 4 + 0 = 4 bits

At i = 3:

  • size = 2^(3+1) = 16
  • Complete groups = 9/16 = 0 groups
  • Each group has: 16/2 = 8 set bits
  • Remaining numbers = 9%16 = 9 > size/2(8), so add (9-8) = 1 extra bit
  • Total = 0 * 8 + 1 = 1 bit
C++
// C++ program to Count set
// bits in an integer
#include <iostream>
#include <algorithm>
using namespace std;

// Count total set bits in all 
// numbers from 1 to n
int countSetBits(int n)  {
    
    // Increment n to include 0.
    n++;
    int res = 0;
    
    // Check for each bit position.
    for (int i=0; i<30; i++) {
        
        // Size of pattern.
        int size = (1<<(i+1));
        
        // Mutiply total groups and 
        // set bits in each group.
        res += ((n/size)*(size/2));
        
        // Bits in last group.
        int rem = n%size;
        
        // Add set bits from last group.
        if (rem-size/2>0) res+= (rem-size/2);
    }
    
    return res;
}

int main() {
	int i = 3;
	cout << countSetBits(i);
	return 0;
}
Java
// Java program to Count set
// bits in an integer

import java.util.*;

class GfG {

    // Count total set bits in all 
    // numbers from 1 to n
    static int countSetBits(int n) {

        // Increment n to include 0.
        n++;
        int res = 0;

        // Check for each bit position.
        for (int i = 0; i < 30; i++) {

            // Size of pattern.
            int size = (1 << (i + 1));

            // Multiply total groups and 
            // set bits in each group.
            res += ((n / size) * (size / 2));

            // Bits in last group.
            int rem = n % size;

            // Add set bits from last group.
            if (rem - size / 2 > 0) res += (rem - size / 2);
        }

        return res;
    }

    public static void main(String[] args) {
        int i = 3;
        System.out.println(countSetBits(i));
    }
}
Python
def count_set_bits(n):
    # Increment n to include 0.
    n += 1
    res = 0
    
    # Check for each bit position.
    for i in range(30):
        # Size of pattern.
        size = 1 << (i + 1)
        
        # Multiply total groups and set bits in each group.
        res += (n // size) * (size // 2)
        
        # Bits in last group.
        rem = n % size
        
        # Add set bits from the last group.
        if rem - size // 2 > 0:
            res += (rem - size // 2)
    
    return res

# Example usage:
i = 3
print(count_set_bits(i))
C#
// C# program to Count set
// bits in an integer

using System;

class GfG {

    // Count total set bits in all 
    // numbers from 1 to n
    static int countSetBits(int n) {

        // Increment n to include 0.
        n++;
        int res = 0;

        // Check for each bit position.
        for (int i = 0; i < 30; i++) {

            // Size of pattern.
            int size = (1 << (i + 1));

            // Multiply total groups and 
            // set bits in each group.
            res += ((n / size) * (size / 2));

            // Bits in last group.
            int rem = n % size;

            // Add set bits from last group.
            if (rem - size / 2 > 0) res += (rem - size / 2);
        }

        return res;
    }

    static void Main(string[] args) {
        int i = 3;
        Console.WriteLine(countSetBits(i));
    }
}
JavaScript
// JavaScript program to Count set
// bits in an integer

// Count total set bits in all 
// numbers from 1 to n
function countSetBits(n) {

    // Increment n to include 0.
    n++;
    let res = 0;

    // Check for each bit position.
    for (let i = 0; i < 30; i++) {

        // Size of pattern.
        let size = (1 << (i + 1));

        // Multiply total groups and 
        // set bits in each group.
        res += ((Math.floor(n / size)) * (size / 2));

        // Bits in last group.
        let rem = n % size;

        // Add set bits from last group.
        if (rem - size / 2 > 0) res += (rem - size / 2);
    }

    return res;
}
// Driver code 

let i = 3;
console.log(countSetBits(i));

Output
4

Next Article
Article Tags :
Practice Tags :

Similar Reads