ตรวจสอบว่า y เป็นกำลังของ x หรือไม่ (y = xᵏ)
ตัวอย่าง: 125 เป็นกำลังของ 5 เพราะ 125 = 5³
อัลกอริทึม
isRepresentPower(x, y):
if x == 1: return (y == 1)
pow = 1
while pow < y: pow *= x
return (pow == y)
ตัวอย่างโค้ด
#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;
return (pow == y);
}
int main() {
int x = 5, y = 125;
cout << (isRepresentPower(x, y) ? "Can be represented" : "Cannot be represented");
}
ผลลัพธ์
Can be represented