简体   繁体   中英

Time complexity calculation of algorithm

What is the complexity of the below program:

void function(int n)
{
int i, j, k , count =0;
for(i=n/2; i<=n; i++)
  for(j=1; j=j + n/2<=n; j++)
      for(k=1; k<=n; k= k * 2)
         count++;
}

Now as per my understanding the outer loop executes n/2 times. Inner loop executes n/2 times and third inner loop executes the log n times. Now if we denote the time complexity of algorithm as a function T(n).

T(n)=n/2 n/2 log n =n^2/4*log n

Now for very large input size of n term log n becomes too small in comparison with the term n^2. So per my understanding the time complexity of the algorithm must be O(n^2). But I have checked the answer of this above program it says the answer is O(n^2logn).

Why can't we ignore the term log n for larger values of n? Or is the calculation I have done wrong?

You can ignore only the constant values. If n increases, log(n) also increases.

If we make assumption that your algorihtm has got running time function (is not exactly true):

T(n)=n/2*n/2*log n =n^2/4*log n= an^2*log(n)

You can do formal asymptotic analysis:

在此处输入图片说明

We can easily proof that we can find c1 and c2 to fulfill:

在此处输入图片说明

So finally you can say that your algorithm has got complexity:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM