0

I am novice in analysising time complexity.some one can help me with the time complexity of below algorithm?

public void test(int n)
{
  int i=1;

   while(i<n)
   {
      int j=1; 
      while (j<i)
      {
         j=j*2;
      }

     i=i*2;
   }
}

outer loop will run log(n) times.How many times the inner loop will run. How can we calulate the frequency of inner loop in terms of "n" because here it depends on variable "i" and will run log(i) times.

Can someone help to find time complexity of above code.

nayak0765
  • 175
  • 2
  • 15

2 Answers2

0

The time complexity of the given function is O(log n log n) = O(log^2 n).

The outer loop has time complexity O(log n). Similarly, the inner loop also has time complexity O(log n) because the value of i is bounded above by n. Hence log i = O(log n).

Deepu
  • 7,592
  • 4
  • 25
  • 47
  • inner loop will execute log1, log2 ,log4 , log 8...for value of i=1,2,4,8... How can we do summation of (log1+log2+log4+log8) – nayak0765 Apr 06 '20 at 14:00
0

Outer loop will run for (log n ) times.

Since inner loop is bound by i. So it will run for log1+log2+log3...log (n-1) times for different values of i. Solving it above can be deduced to

= log(1*2*3...(n-l). (Because log a* log b=log(a*b)

= log((n-1)!). (This is (n-1) factorial)

=(n-1)log(n-1). (because logn!= nlogn)

SO inner loop will have complexity O(nlogn).

So the time complexity of above algo is

logn + nlogn

which is O(nlogn).

nayak0765
  • 175
  • 2
  • 15