-3

I need some help calculating the Big-O running time.

I have attempted to do it after each problem, but not sure if it's done correctly.

Q-1: Given the following code fragment, what is its Big-O running time?

 test = 0

 for i in range(n):

        for j in range(n):

                test= test + i *j

T(n)= c1+n*(n)

= c1+n^2

O(n) ≈ n^2

Q-2: Given3 the following code fragment what is its Big-O running time?

 for i in range(n):

      test=test+1

 for j in range(n):

      test= test - 2

T(n)= c1*n+c2(n*n)

T(n)= c1*n1+c2n^2

O(n) ≈ n^2

Q-3: Given the following code fragment what is its Big-O running time?

 i = n

 while i > 0:

        k=2+2

        i = i // 2

T(n)= n*(c1+c2)

O(n) ≈n

sds
  • 58,617
  • 29
  • 161
  • 278
BK Hasan
  • 121
  • 1
  • 1
  • 9

2 Answers2

2

Q-1

You are right.

for i in range(n) is O(n), nesting means multiplication, so O(n^2) is right.

Q-2

No, sequential evaluation is addition, so two loops in a row is O(n)+O(n)=O(n).

Q-3

No, each iteration halves n, so the complexity is O(log(n)).

sds
  • 58,617
  • 29
  • 161
  • 278
0

First, let's start with your terminology, O(n)≈f(n) is not the right terminology, correct one would be to say T(n) is in O(f(n)), where T(n) is the complexity function of the code, and f(n) is the given complexity, so T(n) is in O(n^2), for example.

First code snap:
This is indeed O(n^2), your analysis is correct.

Second code snap:
This is O(n^2), assuming the second loop is nested within the first (your identation is not clear), again - your analysis is correct.
If this is not the case, then
these are sequential loops - each is taking O(n), so total complexity is the addition of them, which yields O(n) as well.

Third code snap:
This is O(logn). Each iteration halves i until i reaches 0. This happens within log_2(n) steps of dividing it by two.

amit
  • 175,853
  • 27
  • 231
  • 333