Reputation: 19
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.
Upvotes: 1
Views: 1107
Reputation: 14988
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.
Upvotes: 2
Reputation: 120
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;
}
Upvotes: 1