0

the following sample loops have O(n^2) time complexity Can anyone explain me why it is O(n^2)? As it depends on the value of c...

loop 1---

 for (int i = 1; i <=n; i += c) 
 {
    for (int j = 1; j <=n; j += c) 
    {
      // some O(1) expressions
    }
 }

loop 2---

 for (int i = n; i > 0; i -= c) 
 {
    for (int j = i+1; j <=n; j += c)
   {
      // some O(1) expressions
   }
 }

If c=0 ; then it runs infinite number of times , in the similar way if c value is increased then the number of times the inner loops run will be decreased

Can anyone explain it to me?

2
  • should it be i -=c in the second loop ? Commented Jun 11, 2015 at 13:52
  • Yea sorry it is i=i-c Commented Jun 11, 2015 at 13:55

3 Answers 3

1

Each of these parts of code takes a time O(n^2/c^2). c is probably considered a strictly positive constant here and therefore O(n^2/c^2) = O(n^2). But it all depends on the context...

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

1 Comment

Read the second loop again !
1

Big-O notation is a relative representation of the complexity of an algorithm.

Big-O does not says anything about how many iterations your algorithm will make in any case .

It says in worst case your algorithm will be making n squared computations. Which is useful if you have to compare 2 algorithms.

In your code if we assume c to be a constant then it could be ignored from Big-O notation because Big-O is all about comparison and how thing scale. where constants play no role.

But when c is not a constant the correct Big-O notation would be O(n^2/c^2).

Read this awesome explanation of Big-O by cletus .

Comments

0

For every FIXED c, the time is O (n^2). The number of iterations is roughly max (n^2 / c^2, n^2) unless c = 0. n^2 / c^2 is O (n^2) for every fixed n.

If you had code where c was changed during the loop, you might get a different answer.

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.