检查一个数字是否可以表达为x^y (x乘以y次方) 的形式,C++
在这里,我们将检查是否可以将一个数字表示为 xy 的次方形式。假设存在一个数字 125。这可以用 53 来表示。而数字 91 则无法表示为某个整数值的次方形式。
算法
isRepresentPower(num): Begin if num = 1, then return true for i := 2, i2 <= num, increase i by 1, do val := log(a)/log(i) if val – int(val) < 0.0000000001, then return true done return false End
示例
#include<iostream> #include<cmath> using namespace std; bool isRepresentPower(int num) { if (num == 1) return true; for (int i = 2; i * i <= num; i++) { double val = log(num) / log(i); if ((val - (int)val) < 0.00000001) return true; } return false; } int main() { int n = 125; cout << (isRepresentPower(n) ? "Can be represented" : "Cannot be represented"); }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
Can be represented
广告