เราจะมาดูกันว่าตัวเลขเป็นกำลังของอีกจำนวนหนึ่งหรือไม่ สมมติว่าหมายเลข 125 และให้หมายเลข 5 อีก ดังนั้นมันจะกลับมาจริงเมื่อพบว่า 125 ยกกำลัง 5 ในกรณีนี้ มันเป็นความจริง 125 =5 3 .
อัลกอริทึม
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