在 C++ 中找到最接近 n 且能被 m 整除的数字
假设我们有两个整数 n 和 m。我们必须找到最接近 n 且能除以 m 的数字。如果有多个这样的数字,则显示绝对值最大的那个数字。如果 n 完全能被 m 整除,则返回 n。因此,如果 n = 13,m = 4,则输出为 12。
为了解决这个问题,我们可以按照以下步骤操作 −
- 令 q := n/m,且 n1 := m*q
- 如果 n * m > 0,则 n2 := m * (q + 1),否则 n2 := m * (q - 1)
- 如果 |n – n1| < |n – n2|,则返回 n1,否则返回 n2
示例
#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; }
输出
Closest for n = 13, and m = 4: 12 Closest for n = 0, and m = 8: 0 Closest for n = 18, and m = -7: 21
广告