Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Check whether the number has only first and last bits set
Next article icon

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
Try it on GfG Practice
redirect icon

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

Table of Content

  • [Naive Approach] Counting Bits for each number
  • [Expected Approach] Using Pattern Based Approach - O(1) Time and O(1) Space

[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
Check whether the number has only first and last bits set

K

kartik
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Amazon
Practice Tags :
  • Amazon
  • Bit Magic

Similar Reads

    Bit Manipulation for Competitive Programming
    Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag
    15+ min read
    Count set bits in an integer
    Write an efficient program to count the number of 1s in the binary representation of an integer.Examples : Input : n = 6Output : 2Binary representation of 6 is 110 and has 2 set bitsInput : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits[Naive Approach] - One by One CountingTh
    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
    Check whether the number has only first and last bits set
    Given a positive integer n. The problem is to check whether only the first and last bits are set in the binary representation of n.Examples: Input : 9 Output : Yes (9)10 = (1001)2, only the first and last bits are set. Input : 15 Output : No (15)10 = (1111)2, except first and last there are other bi
    4 min read
    Shortest path length between two given nodes such that adjacent nodes are at bit difference 2
    Given an unweighted and undirected graph consisting of N nodes and two integers a and b. The edge between any two nodes exists only if the bit difference between them is 2, the task is to find the length of the shortest path between the nodes a and b. If a path does not exist between the nodes a and
    7 min read
    Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
    Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers.Examples:Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A & B = 2, the
    7 min read
    Unset least significant K bits of a given number
    Given an integer N, the task is to print the number obtained by unsetting the least significant K bits from N. Examples: Input: N = 200, K=5Output: 192Explanation: (200)10 = (11001000)2 Unsetting least significant K(= 5) bits from the above binary representation, the new number obtained is (11000000
    4 min read
    Find all powers of 2 less than or equal to a given number
    Given a positive number N, the task is to find out all the perfect powers of two which are less than or equal to the given number N. Examples: Input: N = 63 Output: 32 16 8 4 2 1 Explanation: There are total of 6 powers of 2, which are less than or equal to the given number N. Input: N = 193 Output:
    6 min read
    Powers of 2 to required sum
    Given an integer N, task is to find the numbers which when raised to the power of 2 and added finally, gives the integer N. Example : Input : 71307 Output : 0, 1, 3, 7, 9, 10, 12, 16 Explanation : 71307 = 2^0 + 2^1 + 2^3 + 2^7 + 2^9 + 2^10 + 2^12 + 2^16 Input : 1213 Output : 0, 2, 3, 4, 5, 7, 10 Exp
    10 min read
    Print bitwise AND set of a number N
    Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i. Examples : Input : N = 5Output : 0, 1, 4, 5 Explanation: 0 &
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences