Computer >> Máy Tính >  >> Lập trình >> C ++

Kiểm tra xem một số có phải là lũy thừa của một số khác trong C ++ hay không

Ở đây chúng ta sẽ thấy, liệu một số có phải là lũy thừa của một số khác hay không. Giả sử một số 125 và một số 5 khác được đưa ra. Vì vậy, nó sẽ trả về true khi thấy rằng 125 là lũy thừa của 5. Trong trường hợp này, nó là true. 125 =5 3 .

Thuật toán

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

Ví dụ

#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");
}

Đầu ra

Can be represented