Program to find the Nth natural number with exactly two bits set
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:
- 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.
- Print the Nth number having two set bits.
Efficient Approach:
- Find the leftmost set bit by finding the partition to which N belongs (Partition ‘i’ has ‘i’ numbers in it).
- 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.
- Note: To set ith bit (i = 0, 1, 2…) in a number K:
k = k | (1<<(i))
- Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findNthNum( long long int N)
{
long long int bit_L = 1, last_num = 0;
while (bit_L * (bit_L + 1) / 2 < N) {
last_num = last_num + bit_L;
bit_L++;
}
int bit_R = N - last_num - 1;
cout << (1 << bit_L) + (1 << bit_R)
<< endl;
}
int main()
{
long long int N = 13;
findNthNum(N);
return 0;
}
|
Java
class GFG{
static void findNthNum( int N)
{
int bit_L = 1 , last_num = 0 ;
while (bit_L * (bit_L + 1 ) / 2 < N) {
last_num = last_num + bit_L;
bit_L++;
}
int bit_R = N - last_num - 1 ;
System.out.print(( 1 << bit_L) + ( 1 << bit_R)
+ "\n" );
}
public static void main(String[] args)
{
int N = 13 ;
findNthNum(N);
}
}
|
Python3
def findNthNum(N):
bit_L = 1 ;
last_num = 0 ;
while (bit_L * (bit_L + 1 ) / 2 < N):
last_num = last_num + bit_L;
bit_L + = 1 ;
bit_R = N - last_num - 1 ;
print (( 1 << bit_L) + ( 1 << bit_R));
if __name__ = = '__main__' :
N = 13 ;
findNthNum(N);
|
C#
using System;
class GFG{
static void findNthNum( int N)
{
int bit_L = 1, last_num = 0;
while (bit_L * (bit_L + 1) / 2 < N) {
last_num = last_num + bit_L;
bit_L++;
}
int bit_R = N - last_num - 1;
Console.Write((1 << bit_L) + (1 << bit_R)
+ "\n" );
}
public static void Main(String[] args)
{
int N = 13;
findNthNum(N);
}
}
|
Javascript
<script>
function findNthNum(N)
{
let bit_L = 1, last_num = 0;
while (bit_L * (bit_L + 1) / 2 < N) {
last_num = last_num + bit_L;
bit_L++;
}
let bit_R = N - last_num - 1;
document.write((1 << bit_L) + (1 << bit_R)
+ "<br>" );
}
let N = 13;
findNthNum(N);
</script>
|
-
Time Complexity : O(Partition of Number)
Auxiliary space: O(1) as it is using constant variables
Last Updated :
16 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...