Cho result và N, tìm số nguyên x sao cho x^N = result.
Ví dụ
- result=25, N=2 → x=5
- result=64, N=3 → x=4
Thuật toán
- Duyệt
itừ 1, kiểm trai^N == result. - Hoặc dùng
pow(result, 1.0/N)làm tròn.
Triển khai C++ (tìm kiếm nhị phân)
#include <bits/stdc++.h>
using namespace std;
int nthRoot(int result, int n) {
int low = 1, high = result;
while (low <= high) {
int mid = low + (high - low) / 2;
long long p = 1;
for (int i = 0; i < n; i++) {
p *= mid;
if (p > result) break;
}
if (p == result) return mid;
if (p < result) low = mid + 1;
else high = mid - 1;
}
return -1; // không phải lũy thừa nguyên chính xác
}
int main() {
cout << nthRoot(64, 6) << endl; // 2 (2^6=64)
return 0;
}
Kết quả
2