Algorithm Analysis

So, I am a little versed in the analysis of algorithms, but I absolutely do not understand how to do this. Can someone please explain this to me? Will it be O (logn)?

for (int i=1; i < n; i*=2)
for (int j=0; j < i; j++)
// do simple operation
+4
source share
4 answers

To find the big O nested loops, you need to follow the steps as in the following example.

For example, let:

n = 10

now the outer loop executes 3 times:

i=2,4 and 8

and inner loops run 3 times for each iteration, e.g.

i=2 it iterates 2 times
i=4 it iterates 4 times
i=8 it iterates 8 times

therefore, the total number of iterations is less than 2 * n, which makes it O (2n), we can neglect the constant factor, therefore its large O is equal to

O(n)
+5
source

Actually O(n)

You can understand it as follows:

  • 2, 4, 8, 16, 32,......, n.
  • n 2n.
  • , O(n), .
+1

-, , -O.

:

for (int i=2; i < n; i*=2)

1 i=2

i*=2, = {2,4,8,16,32,64...}, i 2 ^ x, :

i > n, , 2 ^ x > n, , :

log2 (2 ^ x) = log2 (n)

x = log2 (n)// , i log2 (n) .

for , 2log2 (n) +1 for.

:, , for 2log2 (n) +1

for (int j=0; j < i; j++)

j=0 1

j++ j = {0,1,2,3,4,5,6,7,8....}, j = n, for

2n + 1

, , o :

(2n + 1) * (2log2 () +1)

4nlog2 (n) + 2n + 2log2 (n) + 1

log2 (n) (4n + 2) + 2n +1

, o (log2 (n) (4n + 2) + 2n +1), , O, , :

O (log2 () )

Hope this is clear enough to understand.

Sincerely.

+1
source

Formally, you can perform the following actions:

enter image description here

0
source

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


All Articles