[英]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.