Check if a number N can be expressed as the sum of powers of X or not
Last Updated :
02 Jun, 2021
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”.
Examples:
Input: N = 10, X = 3
Output: Yes
Explanation:
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
Output: No
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:
C++
#include <bits/stdc++.h>
using namespace std;
bool ToCheckPowerofX( int n, int x)
{
while (n > 0) {
int rem = n % x;
if (rem >= 2) {
return false ;
}
n = n / x;
}
return true ;
}
int main()
{
int N = 10, X = 3;
if (ToCheckPowerofX(N, X)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static boolean ToCheckPowerofX( int n, int x)
{
while (n > 0 )
{
int rem = n % x;
if (rem >= 2 )
{
return false ;
}
n = n / x;
}
return true ;
}
public static void main (String[] args)
{
int N = 10 , X = 3 ;
if (ToCheckPowerofX(N, X))
{
System.out.print( "Yes" );
}
else
{
System.out.print( "No" );
}
}
}
|
Python3
def ToCheckPowerofX(n, x):
while (n > 0 ):
rem = n % x
if (rem > = 2 ):
return False
n = n / / x
return True
if __name__ = = '__main__' :
N = 10
X = 3
if (ToCheckPowerofX(N, X)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool ToCheckPowerofX( int n, int x)
{
while (n > 0)
{
int rem = n % x;
if (rem >= 2)
{
return false ;
}
n = n / x;
}
return true ;
}
public static void Main(String []args)
{
int N = 10, X = 3;
if (ToCheckPowerofX(N, X))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function ToCheckPowerofX(n, x)
{
while (n > 0) {
var rem = n % x;
if (rem >= 2) {
return false ;
}
n = n / x;
}
return true ;
}
var N = 10, X = 3;
if (ToCheckPowerofX(N, X)) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...