Find Kth number that can be written as sum of different powers of N
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.
Input: N = 3, K = 4
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
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.
Below is the implementation of the above approach:
Time Complexity: O(log2K)
Space Complexity: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.