用 C++ 找出最接近 ab 的 x 倍數


假設我們有三個整數,a、b 和 x。任務是獲取最接近 ab 的 x 倍數。因此,如果 a = 5,b = 4 和 x = 3,則輸出將為 624。因為 54 = 625,並且 624 是 3 的倍數,最接近 625。

這個任務很簡單。我們必須遵循以下步驟來解決這個問題 −

  • 計算 num := ab
  • 然後查詢 f := num/x 的向下取整
  • 現在左側最接近的元素將是 cl = x * f,右側將為 cr = x * (f + 1)
  • 最後,它們中最近的數字將為 min(num – cl, cr – num)

示例

 動態演示

#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);
}

輸出

Find closest element: 624

更新於:18-12-2019

97 次瀏覽

提升您的 職業生涯

透過完成本課程獲得認證

開始學習
廣告