Cho a, b, x, tìm bội số của x gần a^b nhất. Ví dụ a=5, b=4, x=3 → 624 (5^4=625).
Tính num = a^b, f = floor(num/x). Bội trái cl = x*f, bội phải cr = x*(f+1). Chọn bội gần hơn.
Ví dụ
#include <iostream> #include <cmath> using namespace std; long long getClosest(int a, int b, int x) { long long num = pow(a, b); int f = floor(num / x); long long cl = x * f; long long cr = x * (f + 1); if ((num - cl) < (cr - num)) return cl; else return cr; } int main() { int a = 5, b = 4, x = 3; cout << "Find closest element: " << getClosest(a, b, x); }
Kết quả
Find closest element: 624