Algorithms
Complexity Analysis
GATE 2015
Hard
Consider the following C function:
int fun1(int n) {
int i, j, k, p, q=0;
for (i=1; i<n; ++i) {
p = 0;
for (j=n; j>1; j=j/2)
++p;
for (k=1; k<p; k=k*2)
++q;
}
return q;
}Which one of the following most closely approximates the return value of the function fun1?
- An³
- Bn(log n)²
- Cn log n
- n log(log n)
Explanation
The outer loop runs Θ(n) times. For each outer iteration, the middle loop repeatedly halves j from n down past 1, running Θ(log n) times, so p ends up Θ(log n). The inner loop then repeatedly DOUBLES k from 1 while k<p, running Θ(log p) = Θ(log(log n)) times, incrementing q by that amount each outer iteration. Total q ≈ n · log(log n).
Source: GATE CS 2015 (Session 1 / 7th Feb Shift 1) (2015)
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.