Time complexity of nested for loops

361 views Asked by At

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?

3

There are 3 answers

1
vib On

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...

0
gnasher729 On

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.

0
Namit Sinha On

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 .