Project ForgeSign up free
Algorithms
Complexity Analysis
GATE 2013
Medium

Consider the following function:

int unknown(int n) {
  int i, j, k=0;
  for (i=n/2; i<=n; i++)
    for (j=2; j<=n; j=j*2)
      k = k + n/2;
  return (k);
}

The return value of the function is

  • AΘ(n²)
  • Θ(n²log n)
  • CΘ(n³)
  • DΘ(n³log n)

Explanation

The outer loop runs from i=n/2 to i=n, i.e. Θ(n) iterations. The inner loop doubles j from 2 up to n, i.e. Θ(log n) iterations. Each inner-loop execution adds n/2 to k. Total value of k = (outer iterations) × (inner iterations) × (n/2) = Θ(n) × Θ(log n) × Θ(n) = Θ(n² log n).

Source: GATE CS 2013 (2013)

This question is part of a 15-day revision cycle — sign in and Project Forge will bring it back the day before you'd forget it.

Start revising free