Print first n numbers with exactly two set bits
Last Updated :
12 Dec, 2023
Given a number n, print first n positive integers with exactly two set bits in their binary representation.
Examples :
Input: n = 3
Output: 3 5 6
The first 3 numbers with two set bits are 3 (0011),
5 (0101) and 6 (0110)
Input: n = 5
Output: 3 5 6 9 10 12
A Simple Solution is to consider all positive integers one by one starting from 1. For every number, check if it has exactly two sets bits. If a number has exactly two set bits, print it and increment count of such numbers.
An Efficient Solution is to directly generate such numbers. If we clearly observe the numbers, we can rewrite them as given below pow(2,1)+pow(2,0), pow(2,2)+pow(2,0), pow(2,2)+pow(2,1), pow(2,3)+pow(2,0), pow(2,3)+pow(2,1), pow(2,3)+pow(2,2), .........
All numbers can be generated in increasing order according to higher of two set bits. The idea is to fix higher of two bits one by one. For current higher set bit, consider all lower bits and print the formed numbers.
C++
// C++ program to print first n numbers
// with exactly two set bits
#include <iostream>
using namespace std;
// Prints first n numbers with two set bits
void printTwoSetBitNums(int n)
{
// Initialize higher of two sets bits
int x = 1;
// Keep reducing n for every number
// with two set bits.
while (n > 0)
{
// Consider all lower set bits for
// current higher set bit
int y = 0;
while (y < x)
{
// Print current number
cout << (1 << x) + (1 << y) << " ";
// If we have found n numbers
n--;
if (n == 0)
return;
// Consider next lower bit for current
// higher bit.
y++;
}
// Increment higher set bit
x++;
}
}
// Driver code
int main()
{
printTwoSetBitNums(4);
return 0;
}
Java
// Java program to print first n numbers
// with exactly two set bits
import java.io.*;
class GFG
{
// Function to print first n numbers with two set bits
static void printTwoSetBitNums(int n)
{
// Initialize higher of two sets bits
int x = 1;
// Keep reducing n for every number
// with two set bits
while (n > 0)
{
// Consider all lower set bits for
// current higher set bit
int y = 0;
while (y < x)
{
// Print current number
System.out.print(((1 << x) + (1 << y)) +" ");
// If we have found n numbers
n--;
if (n == 0)
return;
// Consider next lower bit for current
// higher bit.
y++;
}
// Increment higher set bit
x++;
}
}
// Driver program
public static void main (String[] args)
{
int n = 4;
printTwoSetBitNums(n);
}
}
// This code is contributed by Pramod Kumar
Python3
# Python3 program to print first n
# numbers with exactly two set bits
# Prints first n numbers
# with two set bits
def printTwoSetBitNums(n) :
# Initialize higher of
# two sets bits
x = 1
# Keep reducing n for every
# number with two set bits.
while (n > 0) :
# Consider all lower set bits
# for current higher set bit
y = 0
while (y < x) :
# Print current number
print((1 << x) + (1 << y),
end = " " )
# If we have found n numbers
n -= 1
if (n == 0) :
return
# Consider next lower bit
# for current higher bit.
y += 1
# Increment higher set bit
x += 1
# Driver code
printTwoSetBitNums(4)
# This code is contributed
# by Smitha
C#
// C# program to print first n numbers
// with exactly two set bits
using System;
class GFG
{
// Function to print first n
// numbers with two set bits
static void printTwoSetBitNums(int n)
{
// Initialize higher of
// two sets bits
int x = 1;
// Keep reducing n for every
// number with two set bits
while (n > 0)
{
// Consider all lower set bits
// for current higher set bit
int y = 0;
while (y < x)
{
// Print current number
Console.Write(((1 << x) +
(1 << y)) +" ");
// If we have found n numbers
n--;
if (n == 0)
return;
// Consider next lower bit
// for current higher bit.
y++;
}
// Increment higher set bit
x++;
}
}
// Driver program
public static void Main()
{
int n = 4;
printTwoSetBitNums(n);
}
}
// This code is contributed by Anant Agarwal.
JavaScript
<script>
// Javascript program to print first n numbers
// with exactly two set bits
// Prints first n numbers with two set bits
function printTwoSetBitNums(n)
{
// Initialize higher of two sets bits
let x = 1;
// Keep reducing n for every number
// with two set bits.
while (n > 0)
{
// Consider all lower set bits for
// current higher set bit
let y = 0;
while (y < x)
{
// Print current number
document.write((1 << x) + (1 << y) + " ");
// If we have found n numbers
n--;
if (n == 0)
return;
// Consider next lower bit for current
// higher bit.
y++;
}
// Increment higher set bit
x++;
}
}
// Driver code
printTwoSetBitNums(4);
// This code is contributed by Mayank Tyagi
</script>
PHP
<?php
// PHP program to print
// first n numbers with
// exactly two set bits
// Prints first n numbers
// with two set bits
function printTwoSetBitNums($n)
{
// Initialize higher of
// two sets bits
$x = 1;
// Keep reducing n for
// every number with
// two set bits.
while ($n > 0)
{
// Consider all lower set
// bits for current higher
// set bit
$y = 0;
while ($y < $x)
{
// Print current number
echo (1 << $x) + (1 << $y), " ";
// If we have found n numbers
$n--;
if ($n == 0)
return;
// Consider next lower
// bit for current
// higher bit.
$y++;
}
// Increment higher set bit
$x++;
}
}
// Driver code
printTwoSetBitNums(4);
// This code is contributed by Ajit
?>
Output :
3 5 6 9
Time Complexity : O(n)
Auxiliary Space: O(1)
Approach#2: Using while and join
The approach is to start from the integer 3 and check whether the number of set bits in its binary representation is equal to 2 or not. If it has exactly 2 set bits, then add it to the list of numbers with 2 set bits until the list has n elements.
Algorithm
1. Initialize an empty list res to store the integers with exactly two set bits.
2. Initialize an integer variable i to 3.
3. While the length of the list res is less than n, do the following:
a. Check whether the number of set bits in the binary representation of i is equal to 2 or not using the count() method of the string.
b. If the number of set bits is equal to 2, then append i to the list res.
c. Increment i by 1.
4. Return the list res.
C++
#include <iostream>
#include <vector>
using namespace std;
int countSetBits(int num) {
int count = 0;
while (num > 0) {
count += num & 1;
num >>= 1;
}
return count;
}
vector<int> numbersWithTwoSetBits(int n) {
vector<int> res;
int i = 3;
while (res.size() < n) {
if (countSetBits(i) == 2) {
res.push_back(i);
}
i++;
}
return res;
}
int main() {
int n = 3;
vector<int> result = numbersWithTwoSetBits(n);
cout << "Result: ";
for (int i = 0; i < result.size(); i++) {
cout << result[i] << " ";
}
cout << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.ArrayList;
import java.util.List;
public class GFG {
// Function to count the number of set bits (binary 1s)
// in an integer
static int countSetBits(int num)
{
int count = 0;
while (num > 0) {
count += num & 1; // Increment count if the last
// bit is set (1)
num >>= 1; // Right shift to check the next bit
}
return count;
}
// Function to generate 'n' numbers with exactly two set
// bits in their binary representation
static List<Integer> numbersWithTwoSetBits(int n)
{
List<Integer> res = new ArrayList<>();
int i = 3; // Start from 3 as the first number with
// two set bits
while (res.size() < n) {
if (countSetBits(i)
== 2) { // Check if the number has exactly
// two set bits
res.add(
i); // Add the number to the result list
}
i++; // Move to the next number
}
return res;
}
public static void main(String[] args)
{
int n = 3; // Number of numbers with two set bits to
// generate
List<Integer> result = numbersWithTwoSetBits(
n); // Get the generated numbers
for (int num : result) {
System.out.print(
num + " "); // Display the generated numbers
}
System.out.println();
}
}
// This code is contributed by Susobhan Akhuli
Python3
def numbersWithTwoSetBits(n):
res = []
i = 3
while len(res) < n:
if bin(i).count('1') == 2:
res.append(i)
i += 1
return res
n = 3
result = numbersWithTwoSetBits(n)
output_string = ' '.join(str(x) for x in result)
print(output_string)
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to count the number of set bits (binary 1s) in an integer
static int CountSetBits(int num)
{
int count = 0;
while (num > 0)
{
count += num & 1; // Increment count if the last bit is set (1)
num >>= 1; // Right shift to check the next bit
}
return count;
}
// Function to generate 'n' numbers with exactly two set bits in their binary representation
static List<int> NumbersWithTwoSetBits(int n)
{
List<int> res = new List<int>();
int i = 3; // Start from 3 as the first number with two set bits
while (res.Count < n)
{
if (CountSetBits(i) == 2) // Check if the number has exactly two set bits
{
res.Add(i); // Add the number to the result list
}
i++; // Move to the next number
}
return res;
}
static void Main(string[] args)
{
int n = 3; // Number of numbers with two set bits to generate
List<int> result = NumbersWithTwoSetBits(n); // Get the generated numbers
Console.Write("Result: ");
foreach (int num in result)
{
Console.Write(num + " "); // Display the generated numbers
}
Console.WriteLine();
}
}
JavaScript
// Javascript program for the above approach
// Function to count the number of set bits (binary 1s)
// in an integer
function countSetBits(num) {
let count = 0;
while (num > 0) {
count += num & 1; // Increment count if the last
// bit is set (1)
num >>= 1; // Right shift to check the next bit
}
return count;
}
// Function to generate 'n' numbers with exactly two set
// bits in their binary representation
function numbersWithTwoSetBits(n) {
let res = [];
let i = 3; // Start from 3 as the first number with
// two set bits
while (res.length < n) {
if (countSetBits(i) === 2) { // Check if the number has exactly
// two set bits
res.push(i); // Add the number to the result list
}
i++; // Move to the next number
}
return res;
}
// Number of numbers with two set bits to generate
let n = 3;
// Get the generated numbers
let result = numbersWithTwoSetBits(n);
// Display the generated numbers
console.log(result.join(' '));
// This code is contributed by Susobhan Akhuli
Time Complexity: O(n log n), where n is the number of integers with exactly two set bits. This is because we are checking the number of set bits in the binary representation of each integer, which takes O(log n) time.
Space Complexity: O(n), where n is the number of integers with exactly two set bits. This is because we are storing the list of integers with two set bits in memory.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read