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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP