The Wayback Machine - https://web.archive.org/web/20240915042329/https://www.geeksforgeeks.org/program-to-find-the-nth-natural-number-with-exactly-two-bits-set/
Open In App

Program to find the Nth natural number with exactly two bits set

Last Updated : 16 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an integer N, the task is to find the Nth natural number with exactly two bits set. 
Examples: 
 

Input: N = 4 
Output: 9 
Explanation: 
Numbers with exactly two bits set: 3, 5, 6, 9, 10, 12, … 
4th number in this is 9
Input: N = 15 
Output: 48 
 

 

Naive Approach: 
 

  1. Run a loop through all natural numbers, and for each number, check if it has two bits set or not by counting set bits in a number.
  2. Print the Nth number having two set bits.

Efficient Approach: 
 

  1. Find the leftmost set bit by finding the partition to which N belongs (Partition ‘i’ has ‘i’ numbers in it).
  2. To find the other set bit, we’ll have to first find the distance of N from the last number of the previous partition. Based on their difference, we set the corresponding bit.
     

  1. Note: To set ith bit (i = 0, 1, 2…) in a number K: 
     
k = k | (1<<(i))
  1. Below is the implementation of the above approach:
     

C++




// C++ Code to  find the Nth number
// with exactly two bits set
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the Nth number
// with exactly two bits set
void findNthNum(long long int N)
{
 
    long long int bit_L = 1, last_num = 0;
 
    // Keep incrementing until
    // we reach the partition of 'N'
    // stored in bit_L
    while (bit_L * (bit_L + 1) / 2 < N) {
        last_num = last_num + bit_L;
        bit_L++;
    }
 
    // set the rightmost bit
    // based on bit_R
    int bit_R = N - last_num - 1;
 
    cout << (1 << bit_L) + (1 << bit_R)
         << endl;
}
 
// Driver code
int main()
{
    long long int N = 13;
 
    findNthNum(N);
 
    return 0;
}


Java




// Java Code to  find the Nth number
// with exactly two bits set
class GFG{
  
// Function to find the Nth number
// with exactly two bits set
static void findNthNum(int N)
{
  
    int bit_L = 1, last_num = 0;
  
    // Keep incrementing until
    // we reach the partition of 'N'
    // stored in bit_L
    while (bit_L * (bit_L + 1) / 2 < N) {
        last_num = last_num + bit_L;
        bit_L++;
    }
  
    // set the rightmost bit
    // based on bit_R
    int bit_R = N - last_num - 1;
  
    System.out.print((1 << bit_L) + (1 << bit_R)
         +"\n");
}
  
// Driver code
public static void main(String[] args)
{
    int N = 13;
  
    findNthNum(N);
}
}
 
// This code is contributed by Princi Singh


Python3




# Python Code to  find the Nth number
# with exactly two bits set
 
 
# Function to find the Nth number
# with exactly two bits set
def findNthNum(N):
 
    bit_L = 1;
    last_num = 0;
 
    # Keep incrementing until
    # we reach the partition of 'N'
    # stored in bit_L
    while (bit_L * (bit_L + 1) / 2 < N):
        last_num = last_num + bit_L;
        bit_L+=1;
     
 
    # set the rightmost bit
    # based on bit_R
    bit_R = N - last_num - 1;
 
    print((1 << bit_L) + (1 << bit_R));
 
 
# Driver code
if __name__ == '__main__':
    N = 13;
 
    findNthNum(N);
 
 
# This code contributed by PrinciRaj1992


C#




// C# Code to  find the Nth number
// with exactly two bits set
using System;
 
class GFG{
   
// Function to find the Nth number
// with exactly two bits set
static void findNthNum(int N)
{
   
    int bit_L = 1, last_num = 0;
   
    // Keep incrementing until
    // we reach the partition of 'N'
    // stored in bit_L
    while (bit_L * (bit_L + 1) / 2 < N) {
        last_num = last_num + bit_L;
        bit_L++;
    }
   
    // set the rightmost bit
    // based on bit_R
    int bit_R = N - last_num - 1;
   
    Console.Write((1 << bit_L) + (1 << bit_R)
         +"\n");
}
   
// Driver code
public static void Main(String[] args)
{
    int N = 13;
   
    findNthNum(N);
}
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// JavaScript Code to find the Nth number
// with exactly two bits set
 
// Function to find the Nth number
// with exactly two bits set
function findNthNum(N)
{
 
    let bit_L = 1, last_num = 0;
 
    // Keep incrementing until
    // we reach the partition of 'N'
    // stored in bit_L
    while (bit_L * (bit_L + 1) / 2 < N) {
        last_num = last_num + bit_L;
        bit_L++;
    }
 
    // set the rightmost bit
    // based on bit_R
    let bit_R = N - last_num - 1;
 
    document.write((1 << bit_L) + (1 << bit_R)
        + "<br>");
}
 
// Driver code
let N = 13;
findNthNum(N);
 
// This code is contributed by Mayank Tyagi
</script>


  1.  
Output: 

36

 

Time Complexity : O(Partition of Number)

Auxiliary space: O(1) as it is using constant variables
 



Similar Reads

Program to find the Nth natural number with exactly two bits set | Set 2
Given an integer N, the task is to find the Nth natural number with exactly two set bits. Examples: Input: N = 4Output: 9Explanation: Numbers with exactly two set bits are 3, 5, 6, 9, 10, 12, .... The 4th term in this series is 9. Input: N = 15Output: 48Explanation: Numbers with exactly two set bits are 3, 5, 6, 9, 10, 12, 17, 18, 20, 24, 33, 34, 3
7 min read
Print first n numbers with exactly two set bits
Given a number n, print first n positive integers with exactly two set bits in their binary representation.Examples : Input: n = 3Output: 3 5 6The first 3 numbers with two set bits are 3 (0011),5 (0101) and 6 (0110)Input: n = 5Output: 3 5 6 9 10 12A Simple Solution is to consider all positive integers one by one starting from 1. For every number, c
11 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Find Nth smallest number having exactly 4 divisors
Given a positive integer N, the task is to find the Nth smallest number in the sequence which is having exactly 4 divisors. Examples: Input: 4Output: 14Explanation: The numbers in the sequence that has 4 divisors are 6, 8, 10, 14, ..., the fourth number in the sequence is 14. Input: 24Output: 94 Approach: This problem can be solved by observing tha
9 min read
Find Nth smallest number that is divisible by 100 exactly K times
Given two numbers N and K . The task is to find N'th smallest number that is divided by 100 exactly K times.Examples: Input : N = 12, K = 2 Output : 120000 120000 is divisible by 100 exactly 2 times and is the 12 th smallest number also.Input : N = 1000, K = 2 Output : 10010000 Approach: First, find the smallest number that is divisible by 100 exac
5 min read
Largest number less than equal to N having exactly K set bits
Given two positive integers N and K, we need to determine if there exists a positive integer X less than or equal to N such that the number of 1s in the binary representation of X is equal to k (i.e., f(X) = K). If such an X exists, we also need to find the maximum value of X and print -1 if there is no such positive integer X. Constraints: 1 &lt;=
13 min read
Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X &amp; Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X &amp; Y) = M, where ⊕ denotes the Bitwise XOR and &amp; denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n &gt; 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Find the Nth natural number which is not divisible by A
Given two integers A and N, our task is to find the Nth natural number which is not divisible by A. Examples: Input: A = 4, N = 12 Output: 15 Explanation: The series starting from 1 excluding the multiples of A would be 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17 and the 12th term which is not divisible by 4 is 15. Input: A = 3, N = 20 Output: 29 E
5 min read
Count set bits in the Kth number after segregating even and odd from N natural numbers
Given two integers N and K, the task is to find the count of set bits in the Kth number in the Odd-Even sequence made of the number from the range [1, N]. The Odd-Even sequence first contains all the odd numbers from 1 to N and then all the even numbers from 1 to N.Examples: Input: N = 8, K = 4 Output: 3 The sequence is 1, 3, 5, 7, 2, 4, 6 and 8. 4
6 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -&gt; 00111, again flipping 1'st and 2'nd bit -&gt; 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Count subarrays made up of elements having exactly K set bits
Given an array arr[] consisting of N integers and an integer K, the task is to count the number of subarrays possible consisting of elements having exactly K set bits. Examples: Input: arr[] = {4, 2, 1, 5, 6}, K = 2Output: 3Explanation: The subarrays made up of elements having exactly 2 set bits are {5}, {6} and {5, 6}. Input: arr[] = {4, 2, 1, 5,
7 min read
Sum of numbers with exactly 2 bits set
Given a number n. Find the sum of all numbers up to n whose 2 bits are set. Examples: Input : 10 Output : 33 3 + 5 + 6 + 9 + 10 = 33 Input : 100 Output : 762 Naive Approach: Find each number up to n whose 2 bits are set. If its 2 bits are set add it to the sum. C/C++ Code // CPP program to find sum of numbers // upto n whose 2 bits are set #include
8 min read
Generate a circular permutation with number of mismatching bits between pairs of adjacent elements exactly 1
Given two integers N and S, the task is to find a circular permutation of numbers from the range [0, 2(N - 1)], starting with S such that the count of mismatching bits between any pair of adjacent numbers is one. Examples: Input: N = 2, S = 3Output: [3, 2, 0, 1]Explanation: The binary representation of numbers 3, 2, 0 and 1 are "11", "10", "01" and
8 min read
Count of numbers whose 0th and Nth bits are set
Given a positive integer N, the task is to count the numbers that can be represented with N bits and whose 0th and Nth bits are set. Examples: Input: N = 2 Output: 1 All possible 2-bit integers are 00, 01, 10 and 11. Out of which only 11 has 0th and Nth bit set.Input: N = 4 Output: 4 Approach: Out of the given N bits, only two bits need to be set i
3 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Toggle bits of a number except first and last bits
Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite: Find most significant set bit of a number Gene
8 min read
Generate a sequence from first X natural numbers which adds up to S on raising 2 to the power of their lowest set bits
Given two integers X and S, the task is to construct a sequence of distinct integers from the range [1, X] such that the sum of value 2K is equal to S, where K is the position of the first set bit from the end ( 0-based indexing )of the binary representation of each element is S. Examples: Input: X = 3, S = 4Output: 2 3 1Explanation:Summation of 2K
10 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 -&gt; Set bits = 1Binary Representation of 2: 10 -&gt; Set bits = 1Binary Representation of 3: 11 -&gt; Se
15+ min read
Nth natural number after removing all numbers consisting of the digit 9
Given a positive integer N, the task is to find the Nth natural number after removing all the natural numbers containing digit 9. Examples: Input: N = 8Output: 8Explanation:Since 9 is the first natural number that contains the digit 9 and is the 9th natural number, therefore, no removal required to find the 8th natural number, which is 8. Input: N
8 min read
Minimize product of first 2^K–1 Natural Numbers by swapping bits for any pair any number of times
Given a positive integer K, the task is to minimize the positive product of the first (2K - 1) Natural Numbers by swapping the bits at the corresponding position of any two numbers any number of times. Examples: Input: K = 3Output: 1512Explanation: The original product is 5040. The given array in binary notation is {001, 010, 011, 100, 101, 110, 11
5 min read
Program to find last two digits of Nth Fibonacci number
Given a number ‘n’, write a function that prints the last two digits of n-th (‘n’ can also be a large number) Fibonacci number.Examples: Input : n = 65 Output : 65 Input : n = 365 Output : 65 Recommended: Please solve it on “PRACTICE” first, before moving on to the solution. A simple solution is to find n-th Fibonacci number and print its last two
9 min read
Count ways to reach Nth Stairs by taking 1 and 2 steps with exactly one 3 step
Given the number N which denotes the number of stairs, the task is to reach the Nth stair by taking 1, 2 steps any number of times and taking a step of 3 exactly once. Examples: Input: N = 4 Output: 2 Explanation: Since a step of 3 has to be taken compulsorily and only once, There are only two possible ways: (1, 3) or (3, 1) Input: N = 5 Output: 5
11 min read
Find the largest number smaller than integer N with maximum number of set bits
Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples: Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.Input : N = 2 Output : 1 Explanation: 2 in binary r
8 min read
Find next greater number formed with exactly two unique digits for each Array element
Given an array arr[] having N integers, the task is to find the next greater number X i.e, X &gt;= arr[i] for each i in the range [0, N) such that the count of unique digits in X is exactly 2. Example: Input: arr[] = {123, 234}Output: 131 242Explanation: For the given array, 131 is the smallest number greater that 123 having exactly 2 unique digits
11 min read
Finding the Nth term in a sequence formed by removing digit K from natural numbers
Given the integers N, K and an infinite sequence of natural numbers where all the numbers containing the digit K (1&lt;=K&lt;=9) are removed. The task is to return the Nth number of this sequence. Example: Input: N = 12, K = 2Output: 14Explanation: The sequence generated for the above input would be like this: 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14
10 min read
Minimize product of first N - 1 natural numbers by swapping same positioned bits of pairs
Given an integer N, the task is to find the minimum positive product of first N - 1 natural numbers, i.e. [1, (N - 1)], by swapping any ith bit of any two numbers any number of times. Note: N is always a perfect power of 2. Since the product can be very large, print the answer modulo 109 + 7. Examples: Input: N = 4Output: 6Explanation:No swapping o
6 min read
Check if a number has two adjacent set bits
Given a number you have to check whether there is pair of adjacent set bit or not.Examples : Input : N = 67 Output : Yes There is a pair of adjacent set bit The binary representation is 100011 Input : N = 5 Output : No Recommended PracticeNumbers having two adjacent set bitsTry It! A simple solution is to traverse all bits. For every set bit, check
3 min read
Total character pairs from two strings, with equal number of set bits in their ascii value
Given two strings s1 and s2. The task is to take one character from the first string and one character from the second string and check if the ASCII values of both characters have the same number of set bits. Print the total number of such pairs. Examples: Input: s1 = "xcd", s2 = "swa" Output: 1 Only valid pair is (d, a) with ASCII values as 100 an
6 min read