Is runtime o (logn) or o (n)?

I am a little confused by this problem. It seems that with each step the size of the problem decreases by half, which assumes O (logn). But if you really think about it, the number of interactions is just a geometric series of 2 + 4 + 8 + ... less than n, which O (n) suggests. Can anyone suggest their ideas?

for (int i=1; i < n; i=2i)
    for (int j=i; j < n; j++)
        // do something
+4
source share
4 answers

A good way to do this is to calculate the complexity of the inner and outer loops separately. Once you do this, you can simply calculate the product of the two to get the overall complexity.

, , . , , , i , , , O(log n).

, n, , , n, . O(n)

O(n log n)

-1

sum(sum(1, j = (2^i)..n), i = 1..log(n)) = nlog(n) - 2n + log(n) + 2 = O(n log n)

0

O (n log n)

, : n 4, 2 n 64, ouret 6 log2 (n) .

: "do somethings" n "do somethings" n-2 "do somethings" n-log2 (n)

"do somethings" n + n-2 + n-4 +... + n-log2 (n) . n * log2 (n) - (1 + 2 + 4 + 8 +... + log2 (n)) = n * log2 (n) - (2n-1) . o (n log n)

0

, do something - Theta(1), Theta(nlog(n)), U2EF1.

, :

Sum p in [1, logn] (Sum j in [2^p, n] 1) =
Sum p in [1, logn] (n - 2^p) =
nlogn - Sum p in [1, logn] (2^p) =
nlogn - Theta(n) =
Theta(nlogn)

, n . , - " n , 1111, , 2^p p = 1 to log(n), n ".

Theta , , , Theta(nlogn) - Theta(n) = Theta(nlogn).

0

Source: https://habr.com/ru/post/1525353/


All Articles