簡體   English   中英

O(n log log n) 時間復雜度

[英]O(n log log n) time complexity

我在這里有一個簡短的程序:

Given any n:
i = 0;
while (i < n) {
   k = 2;
   while (k < n) {
        sum += a[j] * b[k]
        k = k * k;
   }
   i++;
}

它的漸近運行時間是 O(n log log n)。 為什么會這樣? 我知道整個程序至少會運行 n 次。 但我不確定如何找到 log log n。 內循環取決於 k * k,所以它顯然會小於 n。 如果每次都是 k / 2,它只會是 n log n。 但是你怎么知道答案是 log log n 呢?

對於數學證明,內循環可以寫成:

T(n) = T(sqrt(n)) + 1

w.l.o.g assume 2 ^ 2 ^ (t-1)<= n <= 2 ^ (2 ^ t)=>
we know  2^2^t = 2^2^(t-1) * 2^2^(t-1)
T(2^2^t) = T(2^2^(t-1)) + 1=T(2^2^(t-2)) + 2 =....= T(2^2^0) + t =>
T(2^2^(t-1)) <= T(n) <= T(2^2^t) = T(2^2^0) + log log 2^2^t = O(1) + loglogn

==> O(1) + (loglogn) - 1 <= T(n) <= O(1) + loglog(n) => T(n) = Teta(loglogn).

然后總時間為O(n loglogn)。

為什么內環是T(n)= T(sqrt(n))+1? 首先看內部循環中斷時,當k> n時,表示k之前至少為sqrt(n),或者在最多為sqrt(n)之前的兩個級別,因此運行時間將為T(sqrt(n)) +2≥T(n)≥T(sqrt(n))+ 1。

如果循環變量以指數方式減少/增加恆定量,則循環的時間復雜度為O(log log n)。 如果將循環變量除以/乘以常量,則復雜度為O(Logn)。

例如:在你的情況下,k的值如下。 讓括號中的i表示循環執行的次數。

 2 (0) , 2^2 (1), 2^4 (2), 2^8 (3), 2^16(4), 2^32 (5) , 2^ 64 (6) ...... till n (k) is reached. 
The value of k here will be O(log log n) which is the number of times the loop has executed.

為了假設,我們假設n2^64 現在log (2^64) = 64並且log 64 = log (2^6) = 6.因此,當n2^64時,程序運行了6次。

我想如果代碼是這樣的,應該是 n*log n;

i = 0;
while (i < n) {
    k = 2;
    while (k < n) {
        sum += a[j] * b[k]
        k *= c;// c is a constant bigger than 1 and less than k;
    }
i++;
}
Okay, So let's break this down first -

Given any n:
i = 0;
while (i < n) {
k = 2;
   while (k < n) {
     sum += a[j] * b[k]
     k = k * k;
   }
  i++;
}

1. while( i<n ) will run for n+1 times but we'll round it off to n  
   times.                
2. now here comes the fun part, k<n will not run for n times instead it  
   will run 
   for log log n times because here instead of incrementing k by 1 ,in 
   each loop we  are incrementing it by squaring it. now this means 
   it'll take only log log n time for the loop. you'll understand this 
   when you learn design and analysis of algorithm  

3. Now we combine all the time complexity and we get n.log log n time
   here I hope you get it now. 






     

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM