nevzatseferoglu
nevzatseferoglu

Reputation: 1186

Nested loop analyzing (each loop bounds inner loop)

Question : What is the time-complexity of this algorithm ?

What is the mistake on this table ( if there is ) :

enter image description here

int c = 0;
for (int i = 0; i < n * n; ++i)
    for (int j = 0; j < n; ++j)
        for (int k = 0; k < j * 2; ++k)
            c = c + 1;
return c;

All answers are welcomed.

Upvotes: 2

Views: 133

Answers (1)

chqrlie
chqrlie

Reputation: 144715

In order to compute the time complexity, you can try and evaluate the number of iterations of the innermost loop.

  • the loop on k evaluates a simple expression 2 * j times.
  • the loop on j runs n times. Hence the inner loop runs 2 * n * (n + 1) / 2, which simplifies to n * (n + 1).
  • the outer loop runs n * n times. Hence the inner loops runs exactly n * n * n * (n + 1) times.

Simplifying for the dominant term, the resulting time complexity is n4.

Yet a very shrewd compiler would reduce this complexity to constant time O(1) and generate code for:

return n * n * n * (n + 1);

Trying this on Godbolt's compiler explorer shows that none of the common compilers achieve this as of now, albeit clang goes to great lengths trying to optimize the code with unfathomable SIMD code.

Upvotes: 3

Related Questions