This documentation is automatically generated by online-judge-tools/verification-helper
#include "algorithm/Math/Algebra/nth_root.hpp"
非負の実数 $x$ に対する $n$ 乗根 $\sqrt[n]{x}$ を求める(ただし,$n$ は自然数).
本実装では「ニュートン法」を用いており,近似解を計算する.
#ifndef ALGORITHM_NTH_ROOT_HPP
#define ALGORITHM_NTH_ROOT_HPP 1
#include <cassert>
#include <cmath>
#include "power.hpp"
namespace algorithm {
// 累乗根(ニュートン法).xのn乗根を求める.
constexpr double nth_root(double x, long long n, double eps = 1e-10) {
assert(x >= 0.0);
assert(n >= 1);
double res = 1.0;
while(true) {
double tmp = (x / pow(res, n - 1) + (n - 1) * res) / n;
if(std::abs(tmp - res) < eps) break;
res = tmp;
}
return res;
}
} // namespace algorithm
#endif
#line 1 "algorithm/Math/Algebra/nth_root.hpp"
#include <cassert>
#include <cmath>
#line 1 "algorithm/Math/Algebra/power.hpp"
#line 5 "algorithm/Math/Algebra/power.hpp"
namespace algorithm {
// 繰り返し二乗法.O(logK).
template <typename Type>
constexpr Type pow(Type n, long long k) {
assert(k >= 0);
Type res = 1;
while(k > 0) {
if(k & 1LL) res *= n;
n *= n;
k >>= 1;
}
return res;
}
} // namespace algorithm
#line 8 "algorithm/Math/Algebra/nth_root.hpp"
namespace algorithm {
// 累乗根(ニュートン法).xのn乗根を求める.
constexpr double nth_root(double x, long long n, double eps = 1e-10) {
assert(x >= 0.0);
assert(n >= 1);
double res = 1.0;
while(true) {
double tmp = (x / pow(res, n - 1) + (n - 1) * res) / n;
if(std::abs(tmp - res) < eps) break;
res = tmp;
}
return res;
}
} // namespace algorithm