1

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/2n/2log 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?

5
  • 1
    Yes, log(n) is smaller than polynomial, but when it's multiplied it's still a factor. O(log(n)) is slower than O(n), but O(nlogn) is a thing, and it's similar to what you've got. O(nlogn) != O(n). A graph could illustrate this well. Commented Nov 22, 2014 at 17:38
  • Thanks keyser. Say for example if we have time complexity T(n)=n^3+n^2+n then for very large values of n we ignore the term n^2 and n then why can't we do the same thing over here ? Commented Nov 22, 2014 at 17:41
  • 1
    Yes, we do, because they're separate. Asymptotically the other ones won't have any notable impact, but asymptotically, O(nlogn) grows faster than O(n), since log(n) is more than a constant. I liked benji's illustration of how they're removed. Commented Nov 22, 2014 at 17:42
  • 1
    n^3 + n^2 is less than n^3 + n^3 = 2*n^3 which is O(n^3) Commented Nov 22, 2014 at 17:43
  • 1
    When you multiply you get a different order of magnitude Commented Nov 22, 2014 at 17:44

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks axiac. But say for example if we have time complexity T(n)=n^3+n^2+n then for very large values of n we ignore the term n^2 and n then why can't we do the same thing over here ?
@Beast You can ignore n^2 and n because you add them to n^3 not multiply like in your example.
0

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:

enter image description here

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

enter image description here

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

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.