Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

숫자가 C++에서 다른 숫자의 거듭제곱인지 확인

<시간/>

여기에서 숫자가 다른 숫자의 거듭제곱인지 여부를 알 수 있습니다. 숫자 125와 다른 숫자 5가 주어졌다고 가정합니다. 따라서 125가 5의 거듭제곱임을 발견하면 true를 반환합니다. 이 경우 true입니다. 125 =5 3 .

알고리즘

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

예시

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

출력

Can be represented