检查数字是否是C ++中另一个数字的幂
在这里,我们将看到一个数字是否是另一个数字的幂。假设数字为125,另一个数字为5。因此,当发现125为5的幂时,它将返回true。在这种情况下,它为true。125=53。
算法
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