Processing math: 100%

检查一个数字是否可以表达为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

更新于: 27-Sep-2019

157 次浏览

开启你的 职业生涯

完成课程以获得认证

开始学习
广告