How to calculate Big O nested loops

Im under the impression that to search for a large O of a nested loop, one multiplexes the big O of each forloop with the next for loop. There will be a big O for:

    for i in range(n):
         for j in range(5):
              print(i*j)

be O (5n)? and if it were a big O for:

 for i in range(12345):
      for j in range(i**i**i)
           for y in range (j*i):
                print(i,j,y)

be O(12345*(i**i**i)*(j*i)? Or will it be O(n^3)because its nested 3 times? Im so confusing

+4
source share
3 answers

This is a little simplified, but we hope to get a Big-O value:

Big-O talks about “how many times does my code do something?”, Answering it in algebra and asking “what term does it mean in the end?”

- , print, - 5n times. n 5 . ? n, 5 ! , Big-O O(n).

- , , , . 12345 , , 16 , 7625597484987... 12345^12345^12345. . , , ! , , . , O(1). - , 5n / 5 == n, 12345 / 12345 == 1.

, , ( Big-O, !). :

def more_terms(n):
  for i in range(n):
    for j in range(n):
      print(n)
      print(n)
  for k in range(n):
    print(n)
    print(n)
    print(n)

print 2n^2 + 3n . , n , n , 2 . n 3 . , n^2 + n, ? n - 1, . n , , n^2 , n - O(n^2).

+4

O (n ^ 3) . O, :

1 n. , , O O (n ^ 3). O O (n ^ ( )). - O (n). n, O (5n), O (n).

0

, O (n). , .
O (n) " , n". , .
f g - , f = O (g) , C , n, f (n) C * g (n). "Big O , , , f = O (5n), f = O (n).

0

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


All Articles