[英]Cubic Root Algorithm in O(n) and O(log n) time
我将如何 go 计算 O(n) 时间和 O(log n) 时间的三次根? 时间复杂度为 O(log n) 的算法我会二分查找(我猜)? 任何想法将不胜感激。
对于 O(n),您可以从 0 迭代到 n,检查该数字是否是您要查找的立方根。 (这只适用于整数)
int cubic(int n){
for(int i=0;i<=n;i++)
if(i*i*i==n)
return i;
return -1; // cubic root doesn't exist.
}
对于 O(logn),您可以进行从 0 到 n 的二进制搜索:
double error=0.00000001;
double cubic(double n){
double l=0, r=n, m=(r+l)/2;
while (abs(n-m*m*m)>error){ // if difference between m^3 and n is not satisfactory
m=(r+l)/2;
if(m*m*m<n) // if m^3 < n, then the root is definitely greater then m, so we move the left border
l=m;
else // otherwise, move the right border
r=m;
}
return m;
}
使用Newton-Raphson 方法怎么样? 如果您正在寻找N
的三次根,那么您实际上是在寻找f(x) = x^3 - N
的根。 牛顿法的收敛时间是二次的,复杂度为O(log(n))
。
编辑:更准确地说,如此处所述,它具有O(log(n)F(n))
的复杂性,其中F(n)
是计算具有n
位精度的“更新”的成本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.