โจทย์
ได้รับตัวเลข x และ y ทางเราต้อง หาว่า x^y หรือ y^x ใหญ่กว่ากัน
ตัวอย่าง
Input: x = 4, y = 5
Output: 1024 (เพราะ 4^5 = 1024 > 5^4 = 625)
แนวทางแก้ปัญหา
ใช้ ลอการิทึม เพื่อหลีกเลี่ยงการล้น (Overflow):
- เปรียบเทียบ y*log(x) กับ x*log(y)
- ค่าที่มากกว่าแสดงว่ากำลังนั้นใหญ่กว่า
โปรแกรมตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
double x = 3, y = 7;
double ylogx = y * log(x);
double xlogy = x * log(y);
if (ylogx > xlogy) cout << x << "^" << y;
else if (ylogx < xlogy) cout << y << "^" << x;
else cout << "None";
cout << " has greater value";
return 0;
}
ผลลัพธ์
3^7 has greater value