Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตรวจสอบว่าตัวเลขสามารถแสดงเป็นกำลังใน C++ . ได้หรือไม่


ที่นี่เราจะตรวจสอบว่าเราสามารถแสดงตัวเลขเป็นกำลังได้หรือไม่ เช่น a b หรือไม่. สมมุติว่ามีเลข 125 สามารถแสดงเป็น 5 3 . ไม่สามารถแสดงเลข 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");
}

ผลลัพธ์

Can be represented