Check if a number N can be expressed as the sum of powers of X or not
Given two positive numbers N and X, the task is to check if the given number N can be expressed as the sum of distinct powers of X. If found to be true, then print “Yes”, Otherwise, print “No”.
Input: N = 10, X = 3
The given value of N(= 10) can be written as (1 + 9) = 30 + 32. Since all the power of X(= 3) are distinct. Therefore, print Yes.
Input: N= 12, X = 4
Approach: The given problem can be solved by checking if the number N can be written in base X or not. Follow the steps below to solve the problem:
- Iterate a loop until the value of N is at least 0 and perform the following steps:
- Calculate the value of remainder rem when N is divided by X.
- If the value of rem is at least 2, then print “No” and return.
- Otherwise, update the value of N as N / X.
- After completing the above steps, if there doesn’t exist any termination, then print “Yes” as the result at N can be expressed in the distinct power of X.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: 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.