简体   繁体   中英

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? The algorithm that has a time complexity of O(log n) I would would binary search (I'm guessing)? 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. (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:

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 ? If you're looking for a cubic root of N than you're essentially looking at a root of f(x) = x^3 - N . The convergence of Newton's method is quadratic in time and the complexity would be 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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