在 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

更新於:19-12-2019

1 千次以上瀏覽

開啟你的職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.