# C++ Representation of a Number in Powers of Other

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Discuss the problem of representing a number in the power of another number. We are given two numbers, x, and y. We need to tell whether y can be represented in the power of x where each power of x can be used once, for example

Input: x = 4, y = 11
Output: true
Explanation: 4^2 - 4^1 - 4^0 = 11 Hence y can be represented in the power of x.

Input: x = 2, y = 19
Output: true
Explanation: 2^4 + 2^1 + 2^0 =19 Hence y can be represented in the power of x.

Input: x = 3, y = 14
Output: false
Explanation: 14 can be represented as 3^2 + 3^1 + 3^0 + 3^0 but we cannot use one term of power of x twice.

## Approach to Find the Solution

From examining the example on how 19 is represented in the terms of the power of 2 we can form an equation −

c0(x^0) + c1(x^1) + c2(x^2) + c3(x^3) + … = y ….(1),

Where c0, c1, c2 can be -1, 0, +1 to represent whether (-1)term to be subtracted, (+1)term to be added, (0)term not to be included −

c1(x^1) + c2(x^2) + c3(x^3) + … = y - c0,

Taking x as common,

c1(x^0) + c2(x^1) + c3(x^2) + … = (y - c0)/x ….(2),

From eq (1) and (2) we can represent the number in the way again and for a solution to exist (y - Ci) should be divisible by x and Ci can only contain -1, 0 and +1.

So finally we need to check till y>0 whether [(y-1) % x == 0] or [(y) % x == 0] or [(y+1) % x == 0] or whether a solution does not exist.

## Example

#include <bits/stdc++.h>
using namespace std;
int main(){
int x = 2, y = 19;
// checking y divisibility till y>0
while (y>0) {
// If y-1 is divisible by x.
if ((y - 1) % x == 0)
y = (y - 1) / x;
// If y is divisible by x.
else if (y % x == 0)
y = y / x;
// If y+1 is divisible by x.
else if ((y + 1) % x == 0)
y = (y + 1) / x;
// If no condition satisfies means
// y cannot be represented in terms of power of x.
else
break;
}
if(y==0)
cout<<"y can be represented in terms of the power of x.";
else
cout<<"y cannot be represented in terms of the power of x.";
return 0;
}

## Output

y can be represented in terms of the power of x.

## Conclusion

In this tutorial, we discussed how to check if the representation of a number is possible in terms of the power of another number. We discussed a simple approach to solve this problem by checking current, preceding, and succeeding number divisibility with y.

We also discussed the C++ program for this problem which we can do with programming languages like C, Java, Python, etc. We hope you find this tutorial helpful.

Updated on 26-Nov-2021 06:53:38