简体   繁体   English

O(n) 和 O(log n) 时间的三次根算法

[英]Cubic Root Algorithm in O(n) and O(log n) time

How would I go about calculating the cubic root in O(n) time and O(log n) time?我将如何 go 计算 O(n) 时间和 O(log n) 时间的三次根? The algorithm that has a time complexity of O(log n) I would would binary search (I'm guessing)?时间复杂度为 O(log n) 的算法我会二分查找(我猜)? Any ideas would be much appreciated.任何想法将不胜感激。

For O(n) you can just iterate from 0 to n, checking if the number is the cubic root you're looking for.对于 O(n),您可以从 0 迭代到 n,检查该数字是否是您要查找的立方根。 (This only works with integers) (这只适用于整数)

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.
}

For O(logn) you can do a binary search from 0 to n:对于 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;
}

What about using Newton–Raphson method ?使用Newton-Raphson 方法怎么样? If you're looking for a cubic root of N than you're essentially looking at a root of f(x) = x^3 - N .如果您正在寻找N的三次根,那么您实际上是在寻找f(x) = x^3 - N的根。 The convergence of Newton's method is quadratic in time and the complexity would be O(log(n)) .牛顿法的收敛时间是二次的,复杂度为O(log(n))

EDIT: More precisely, as described here it has a complexity of O(log(n)F(n)) where F(n) is the cost of calculating the "update" with n -digit precision.编辑:更准确地说,如此处所述,它具有O(log(n)F(n))的复杂性,其中F(n)是计算具有n位精度的“更新”的成本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM