[英]What is the big O for the complexity O(sqrt(n) * log(sqrt(n))) + O(n)
[英]What is the running time of the algorithm? is it O(sqrt(n)) or O(log(n))?
編輯:約束值范圍 [2,1000000000] 和 a<=b
def sqrtoccurrence(a: Int, b: Int): Int = {
val sqrtA = Math.ceil(Math.sqrt(a)).toInt
val sqrtB = Math.floor(Math.sqrt(b)).toInt
if(sqrtA > sqrtB) 0
else 1 + sqrtoccurrence(sqrtA, sqrtB)
}
是 O(sqrt(n)) 還是 O(log(n))? 我不擅長計算遞歸運行時間。 我知道它的樹的深度以及遞歸函數被調用的次數。 在這種情況下,常量工作 sqrt 有多大影響,是否可以忽略它? 但也許我錯了。 幫助很大的解釋。 謝謝
這是我如何推理必要的運行時間。 在a > b
的最佳情況下,不需要遞歸,因此它是O(1)
操作。 當a <= b
使ceil(sqrt(a)) > floor(sqrt(b))
可能的唯一方法是a
和b
的重復sqrt()
將它們的差異減小到小於舍入誤差.
在最壞的情況下,我們正在研究大b
的重復sqrt()
如何“縮小”以滿足小a
的終止要求。 因此,我將函數在輸入n
上的運行時間描述為:
T(n) = T(sqrt(n)) + C // where C is O(1)
為了計算必要遞歸的近似數量r
,我們可以查看遞歸結束時n
的重復sqrt()
的最終值,比如m
,並建立一個具有以下邏輯的方程:
m
是應用的結果sqrt()
到n
為r
倍
因此,
(..(m^2)^2)^2 ... )^2 = n // `r` times of `^2`
IE
m^(2^r) = n
這意味着:
2^r = log(n) // log base `m`
r = log(log(n)) // outer log base `2`
因此,時間復雜度為O(log(log(n)))
。
sqrtoccurrence(2, 10) // 1
sqrtoccurrence(2, 100) // 2
sqrtoccurrence(2, 1000) // 3
sqrtoccurrence(2, 1000000) // 4
sqrtoccurrence(2, Int.MaxValue) // 4
def log2(x: Double): Double = math.log(x) / math.log(2)
log2(log2(10)) // 1.732
log2(log2(100)) // 2.732
log2(log2(1000)) // 3.317
log2(log2(1000000)) // 4.317
log2(log2(Int.MaxValue)) // 4.954
從另一個答案我們有
T(n) = T(sqrt(n)) + C
現在讓
2^m = n
重寫
T(2^m) = T(sqrt(2^m)) + C
= T(2^(m/2)) + C
讓我們定義一個新函數
S(m) = T(2^m)
然后
S(m) = T(2^m)
= T(2^(m/2)) + C
= S(m/2) + 2C
我們現在知道
S(m) = O(log m)
所以
T(n) = T(2^m) = S(m) = O(log m) = O(log log n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.