Check if a number is a power of another number in C++


Here we will see, whether a number is power of another number or not. Suppose a number 125, and another number 5 is given. So it will return true when it finds that 125 is power of 5. In this case it is true. 125 = 53.

Algorithm

isRepresentPower(x, y):
Begin
   if x = 1, then
      if y = 1, return true, otherwise false
   pow := 1
   while pow < y, do
      pow := pow * x
   done
   if pow = y, then
      return true
   return false
End

Example

 Live Demo

#include<iostream>
#include<cmath>
using namespace std;
bool isRepresentPower(int x, int y) {
   if (x == 1)
      return (y == 1);
      long int pow = 1;
   while (pow < y)
      pow *= x;
   if(pow == y)
   return true;
   return false;
}
int main() {
   int x = 5, y = 125;
   cout << (isRepresentPower(x, y) ? "Can be represented" : "Cannot be represented");
}

Output

Can be represented

Updated on: 27-Sep-2019

487 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements