C++ 中數字的 N 次方根


已知 N 次方根和結果。需要找到一個數字,使得該數字N 等於結果。

看幾個示例。

輸入

result = 25
N = 2

輸出

5

52 = 25。因此上例中的輸出為 5。

輸入

result = 64
N = 3

輸出

4

43 = 64。因此上例中的輸出為 4。

演算法

實現

以下是上述演算法在 C++ 中的實現

#include <bits/stdc++.h>

using namespace std;

int getNthRoot(int result, int n) {
   int i = 1;
   while (true) {
      if (pow(i, n) == result) {
         return i;
      }
      i += 1;
   }
}
int main() {
   int result = 64, N = 6;
   cout << getNthRoot(result, N) << endl;
   return 0;
}

輸出

如果執行上述程式碼,將會獲得以下結果。

2

更新於: 2021 年 10 月 22 日

776 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.