in Algorithms closed by
3,440 views
0 votes
0 votes
closed as a duplicate of: TIME COMPLEXITY

What is time complexity of fun()?

int fun(int n)

{

  int count = 0;

  for (int i = n; i > 0; i /= 2)

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

        count += 1;

  return count;

}

(A) O(n^2)
(B) O(nLogn)
(C) O(n)
(D) O(nLognLogn)

in Algorithms closed by
3.4k views

4 Comments

edited by
simply unroll the dependency..

when i=n ,j will run n times

i=n/2, j will run n/2 times

i=n/4, j=n/4

i=n/8,j=n/8

-----------------------

Total Complexity = n + n/2 + n/4 + n/8 .............. = n(1 + 1/2 +1/4 + 1/8............ logn times) = O(n)

(1 + 1/2 +1/4 + 1/8............ logn times) this value will be nearly 1.
0
0
what is the equation of log n.
0
0
edited by

i think you got it

3
3

1 Answer

1 vote
1 vote
in this problem ...how many times for loop will execute:

       first time loop:  n times

      second time :   n/2 times

        similarly  form series   =    n +n/2 +n/4 + .....+1

                 its decreasing GP series

      TC =   O(n)

Hence option C is correct

Related questions

1 vote
1 vote
1 answer
3
thor asked in Algorithms Nov 23, 2016
590 views
thor asked in Algorithms Nov 23, 2016
by thor
590 views
0 votes
0 votes
1 answer
4
rsansiya111 asked in DS Dec 18, 2021
383 views
rsansiya111 asked in DS Dec 18, 2021
383 views