Cho a, b, x. Tìm bội của x gần nhất với a^b. x=4, a=3, b=3, kết quả 28 vì gần 3³=27 nhất.
Cách làm:
- Nếu b<0 và a=1, a^b=1, bội gần nhất 0 hoặc x.
- Nếu b<0 và a>1, a^b<1, bội gần nhất 0.
- Nếu b>0, tính a^b. mul = floor(a^b/x), bội gần là mul*x hoặc (mul+1)*x.
Ví dụ mã nguồn
#include<iostream> #include<cmath> using namespace std; void findMultiple(int a, int b, int x) { cout << "Nearest multiple: "; if (b < 0) { if (a == 1 && x == 1) cout << "1"; else cout << "0"; } int mul = pow(a, b); int ans = mul / x; int ans1 = x * ans; int ans2 = x * (ans + 1); if((mul - ans1) <= (ans2 - mul)){ cout << ans1; } else{ cout << ans2; } } int main() { int a = 3, b = 3, x = 4; findMultiple(a, b, x); } Kết quả
Nearest multiple: 28