Find Kth number that can be written as sum of different powers of N
Last Updated :
13 Dec, 2021
Given two positive integers N and K. The task is to find the Kth number that can be written as the sum of different non-negative powers of N.
Examples:
Input: N = 3, K = 4
Output: 9
Explanation:
First number that can be written as sum of powers of 3 is [1 = 30]
Second number that can be written as sum of powers of 3 is [3 = 31]
Third number that can be written as sum of powers of 3 is [4 = 30 + 31]
Fourth number that can be written as sum of powers of 3 is [9 = 32]
Therefore answer is 9.
Input: N = 2, K = 12
Output: 12
Approach: This problem can be solved by using the concept of decimal to binary conversion. The idea is to find the binary representation of K and start iterating from the least significant bit to the most significant bit. If the current bit is set then include the corresponding power of N to the answer otherwise skip that bit. Refer to the picture below for a better understanding.
Example: When N = 3, K = 9
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int FindKthNum( int n, int k)
{
int ans = 0;
int currPowOfN = 1;
while (k) {
if (k & 1) {
ans = ans + currPowOfN;
}
currPowOfN = currPowOfN * n;
k = k / 2;
}
return ans;
}
int main()
{
int N = 3;
int K = 4;
cout << FindKthNum(N, K);
}
|
Java
class GFG
{
static int FindKthNum( int n, int k)
{
int ans = 0 ;
int currPowOfN = 1 ;
while (k > 0 )
{
if ((k & 1 ) == 1 ) {
ans = ans + currPowOfN;
}
currPowOfN = currPowOfN * n;
k = k / 2 ;
}
return ans;
}
public static void main(String []args)
{
int N = 3 ;
int K = 4 ;
System.out.println(FindKthNum(N, K));
}
}
|
Python3
def FindKthNum(n, k):
ans = 0
currPowOfN = 1
while (k > 0 ):
if ((k & 1 ) = = 1 ) :
ans = ans + currPowOfN
currPowOfN = currPowOfN * n
k = k / / 2
return ans
N = 3
K = 4
print (FindKthNum(N, K));
|
C#
using System;
class GFG
{
static int FindKthNum( int n, int k)
{
int ans = 0;
int currPowOfN = 1;
while (k > 0)
{
if ((k & 1) == 1) {
ans = ans + currPowOfN;
}
currPowOfN = currPowOfN * n;
k = k / 2;
}
return ans;
}
public static void Main()
{
int N = 3;
int K = 4;
Console.WriteLine(FindKthNum(N, K));
}
}
|
Javascript
<script>
function FindKthNum(n, k)
{
let ans = 0;
let currPowOfN = 1;
while (k)
{
if (k & 1)
{
ans = ans + currPowOfN;
}
currPowOfN = currPowOfN * n;
k = Math.floor(k / 2);
}
return ans;
}
let N = 3;
let K = 4;
document.write(FindKthNum(N, K));
</script>
|
Time Complexity: O(log2K)
Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...