检查一个数字是否为 C++ 中其他数字的幂
这里将演示如何检查一个数字是否是另一个数字的幂。假设一个数字为 125,另一个数字为 5。当发现 125 是 5 的幂时,就会返回 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP