Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Count set bits in an integer
Next article icon

Count numbers in the range [L, R] having only three set bits

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N pairs, where each array element denotes a query of the form {L, R}, the task is to find the count of numbers in the range [L, R], having only 3-set bits for each query {L, R}.

Examples:

Input: arr[] = {{11, 19}, {14, 19}}
Output: 4
             2
Explanation: 

  1. Query(11, 19): Numbers in the range [11, 19] having three set bits are {11, 13, 14, 19}.
  2. Query(14, 19): Numbers in the range [14, 19] having three set bits are {14, 19}.

Input: arr[] = {{1, 10}, {6, 12}}
Output: 1
              2
Explanation: 

  1. Query(1, 10): Numbers in the range [1, 10] having three set bits are {7}.
  2. Query(6, 12): Numbers in the range [6, 12] having three set bits are {7, 11}.

Approach: The idea to solve this problem is to do a pre-computation and store all the numbers with only 3 bits set in the range [1, 1018], and then use binary search to find the position of lowerbound of L and upperbound of R and return the answer as their difference. Follow the steps below to solve the given problem:

  • Initialize a vector, say V, to store all the numbers in the range [1, 1018] with only three bits set.
  • Iterate over every triplet formed of the relation [0, 63]×[0, 63]×[0, 63] using variables i, j, and k and perform the following steps:
    • If i, j, and k are distinct, then compute the number with the ith, jth, and kth bit set, and if the number is less than 1018, push the number in the vector V.
  • Sort the vector V in ascending order.
  • Traverse the array arr[], using the variable i, and perform the following steps:
    • Store the boundaries of the query in the variables, say L and R, respectively.
    • Find the position of the lowerbound of L and upperbound of R in the vector V.
    • Print the difference between the positions of the upper bound of R and the lower bound of L, as the result.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to precompute void precompute(vector<long long>& v) {     // Iterate over the range [0, 64]     for (long long i = 0; i < 64; i++) {         // Iterate over the range [0, 64]         for (long long j = i + 1; j < 64; j++) {             // Iterate over the range [0, 64]             for (long long k = j + 1; k < 64; k++) {                  // Stores the number with set bits                 // i, j, and k                 long long int x                     = (1LL << i) | (1LL << j) | (1LL << k);                  // Check if the number is less                 // than 1e18                 if (x <= 1e18 && x > 0)                     v.push_back(x);             }         }     }      // Sort the computed vector     sort(v.begin(), v.end()); }  // Function to count number in the range // [l, r] having three set bits long long query(long long l, long long r,                 vector<long long>& v) {     // Find the lowerbound of l in v     auto X = lower_bound(v.begin(), v.end(), l);      // Find the upperbound of l in v     auto Y = upper_bound(v.begin(), v.end(), r);      // Return the difference     // in their positions     return (Y - X); } void PerformQuery(vector<pair<long long, long long> > arr,                   int N) {      // Stores all the numbers in the range     // [1, 1e18] having three set bits     vector<long long> V;      // Function call to perform the     // precomputation     precompute(V);      // Iterate through each query     for (auto it : arr) {         long long L = it.first;         long long R = it.second;          // Print the answer         cout << query(L, R, V) << "\n";     } }  // Driver Code int main() {      // Input     vector<pair<long long, long long> > arr         = { { 11, 19 }, { 14, 19 } };     int N = arr.size();      // Function call     PerformQuery(arr, N);      return 0; } 
Java
import java.util.ArrayList; import java.util.Collections; import java.util.List;  public class Main {      // Function to precompute     public static void precompute(List<Long> v) {         // Iterate over the range [0, 64]         for (long i = 0; i < 64; i++) {             // Iterate over the range [0, 64]             for (long j = i + 1; j < 64; j++) {                 // Iterate over the range [0, 64]                 for (long k = j + 1; k < 64; k++) {                      // Stores the number with set bits i, j, and k                     long x = (1L << i) | (1L << j) | (1L << k);                      // Check if the number is less than 10^18                     if (x <= 1000000000000000000L && x > 0)                         v.add(x);                 }             }         }          // Sort the computed list         Collections.sort(v);     }      // Function to count number in the range [l, r] having three set bits     public static long query(long l, long r, List<Long> v) {         // Find the lower bound of l in v         int X = Collections.binarySearch(v, l);         if (X < 0) X = -X - 1;          // Find the upper bound of r in v         int Y = Collections.binarySearch(v, r);         if (Y < 0) Y = -Y - 1;         else Y = Y + 1;          // Return the difference in their positions         return (Y - X);     }      public static void performQuery(List<long[]> arr, int N) {          // Stores all the numbers in the range [1, 10^18] having three set bits         List<Long> V = new ArrayList<>();          // Function call to perform the precomputation         precompute(V);          // Iterate through each query         for (long[] it : arr) {             long L = it[0];             long R = it[1];              // Print the answer             System.out.println(query(L, R, V));         }     }      // Driver Code     public static void main(String[] args) {          // Input         List<long[]> arr = new ArrayList<>();         arr.add(new long[]{11, 19});         arr.add(new long[]{14, 19});         int N = arr.size();          // Function call         performQuery(arr, N);     } } 
Python
# Python3 code to implement the approach import bisect  # Function to precompute def precompute(v):          # Iterate over the range [0, 64]     for i in range(64):                # Iterate over the range [0, 64]         for j in range(i + 1, 64):                        # Iterate over the range [0, 64]             for k in range(j + 1, 64):                                  # Store the number with i, j, k bits set                 x = (1 << i) | (1 << j) | (1 << k)                                  # Check if the number is in valid range                 if x <= 1e18 and x > 0:                     v.append(x)     v.sort()  # Function to compute numbers in the range [l, r] # with three set bits def query(l, r, v):          # Finding lowerbound of l in v     x = bisect.bisect_left(v, l)          # Finding upperbound of l in v     y = bisect.bisect_right(v, r)          # Find difference between positions     return y - x  # This function performs the queries def perform_query(arr):          # Stores the numbers     v = []          # Function call to perform the precomputation     precompute(v)          # Iterate over the query     for l, r in arr:                  # Print the answer         print(query(l, r, v))  # Driver code arr = [(11, 19), (14, 19)]  # Function call perform_query(arr)  # This code is contributed by phasing17. 
C#
using System; using System.Collections.Generic;  public class MainClass {      // Function to precompute     public static void Precompute(List<long> v) {         // Iterate over the range [0, 64]         for (long i = 0; i < 64; i++) {             // Iterate over the range [0, 64]             for (long j = i + 1; j < 64; j++) {                 // Iterate over the range [0, 64]                 for (long k = j + 1; k < 64; k++) {                      // Stores the number with set bits i, j, and k                     long x = (1L << (int)i) | (1L << (int)j) | (1L << (int)k);                      // Check if the number is less than 10^18                     if (x <= 1000000000000000000L && x > 0)                         v.Add(x);                 }             }         }          // Sort the computed list         v.Sort();     }      // Function to count number in the range [l, r] having three set bits     public static long Query(long l, long r, List<long> v) {         // Find the lower bound of l in v         int X = v.BinarySearch(l);         if (X < 0) X = ~X;          // Find the upper bound of r in v         int Y = v.BinarySearch(r);         if (Y < 0) Y = ~Y;         else Y = Y + 1;          // Return the difference in their positions         return (Y - X);     }      public static void PerformQuery(List<long[]> arr, int N) {          // Stores all the numbers in the range [1, 10^18] having three set bits         List<long> V = new List<long>();          // Function call to perform the precomputation         Precompute(V);          // Iterate through each query         foreach (var it in arr) {             long L = it[0];             long R = it[1];              // Print the answer             Console.WriteLine(Query(L, R, V));         }     }      // Driver Code     public static void Main(string[] args) {          // Input         List<long[]> arr = new List<long[]>();         arr.Add(new long[]{11, 19});         arr.Add(new long[]{14, 19});         int N = arr.Count;          // Function call         PerformQuery(arr, N);     } } 
JavaScript
// Javascript code to implement the approach  // Function to precompute function precompute(v) {      // Iterate over the range [0, 64]     for (let i = 0; i < 64; i++)      {              // Iterate over the range [0, 64]         for (let j = i + 1; j < 64; j++)          {                      // Iterate over the range [0, 64]             for (let k = j + 1; k < 64; k++)              {                              // Store the number with i, j, k bits set                 let x = BigInt(2n ** BigInt(i)) | BigInt(2n ** BigInt(j)) | BigInt(2n ** BigInt(k));                                  // Check if the number is in valid range                 if (x <= BigInt(1e18) && x > 0n) {                     v.push(x);                 }             }         }     }     v.sort((a, b) => {         if (a > b) {             return 1;         } else if (a < b) {             return -1;         } else {             return 0;         }     }); }  // Function to compute numbers in the range [l, r] // with three set bits function query(l, r, v)  {      // Finding lowerbound of l in v     let x = v.findIndex(n => n >= l);          // Finding upperbound of l in v     let y = v.findIndex(n => n > r);          // Find difference between positions     return y - x; }  // This function performs the queries function performQuery(arr)  {      // Stores the numbers     let v = [];          // Function call to perform the precomputation     precompute(v);          // Iterate over the query     for (const [l, r] of arr)     {              // Print the answer         console.log(query(l, r, v));     } }  // Driver code let arr = [     [11, 19],     [14, 19] ];  // Function call performQuery(arr);  // This code is contributed by phasing17. 

Output
4 2

Time Complexity: O(N*log(633)+ 633)
Auxiliary Space: O(633)



Next Article
Count set bits in an integer

U

UtkarshPandey6
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Mathematical
  • Bit Algorithms
  • setBitCount
Practice Tags :
  • Bit Magic
  • Mathematical

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 bits Input : n = 13Output : 3Binary representation of 13 is 1101 and has 3 set bits [Naive Approach] - One by One Counting
    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, t
    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