Cho n, m, tìm số gần n nhất chia hết cho m. Nếu nhiều hơn một, lấy số có giá trị tuyệt đối lớn nhất. Nếu n chia hết m thì trả về n. Ví dụ n=13, m=4 → 12.
Các bước: q = n/m, n1 = m*q. Nếu n*m > 0 thì n2 = m*(q+1) ngược lại n2 = m*(q-1). So sánh |n-n1| và |n-n2|.
Ví dụ
#include<iostream> #include<cmath> using namespace std; int findClosest(int n, int m) { int q = n / m; int n1 = m * q; int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1)); if (abs(n - n1) < abs(n - n2)) return n1; return n2; } int main() { int n = 13, m = 4; cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl; n = 0; m = 8; cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl; n = 18; m = -7; cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl; }
Kết quả
Closest for n = 13, and m = 4: 12 Closest for n = 0, and m = 8: 0 Closest for n = 18, and m = -7: 21