retagged by
647 views
0 votes
0 votes
m=1;

for i=1 to n do begin

        m=m*3;

        for j=1 to m do

               {Something which is O(1)}

What is the complexity of above algorithm?

1. O(n*m3)

2. O(n3)

3. O(3n)

4. O(3m)
retagged by

3 Answers

Best answer
2 votes
2 votes

Outer Loop Run                  Inner Loop Run

  i=1, m=3                       j=(1 to 3)  i.e Total 3 times

i=2, m=3^2                    j=(1 to 3)  i.e Total 3^2 times

i=3, m=3^3                    j=(1 to 3^3)  i.e Total 3^3 times

                         .

                         .

i=n, m=3^n                    j=(1 to 3^n)  i.e Total 3^n times

Total Number of times loop executes = 3+ 3^2+ 3^3 + 3^4 ......+3^n

                                                    =3(3^n-1)/(3-1)

                                                    =O(3^n)

selected by
0 votes
0 votes
option C
0 votes
0 votes

Option C is correct.

The complexity depends upon how many times the innermost loop run in this case

Just dry run the program using initial values and we can observe the pattern formed and can be calculated easily.

Sorry for handwriting and clarity :)

Hope it helps :)

Answer:

Related questions

0 votes
0 votes
1 answer
1
Overflow04 asked Oct 9, 2022
415 views
how O($n^{2}$) in the last.(in the given solution).
0 votes
0 votes
0 answers
2
Overflow04 asked Oct 9, 2022
285 views
Is it really coping operation will take O(n).Does copy is done character by character.means simple code like (in c++) for(int i=0;i<n;i++){s=s;}will take O($n^{2}$)
0 votes
0 votes
0 answers
3
Overflow04 asked Oct 9, 2022
340 views
I am not getting the question.(Please explain me the question first).
1 votes
1 votes
2 answers
4
Nitesh_Yadav asked Apr 11, 2022
275 views
What is the time complexity of the below mentioned recursive function.int f(n){ if(n!=1){ return f(n/2)+f(n/2);}elsereturn 10;} O(n)O(n^2)O(log n)O(n logn)