Skip to content
Official PYQ · 2015

GATE CS 2015 Set 1 Q31 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

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\text{fun1}?

Choose one option
View worked solution

Answer: D

To find the return value of the function fun1(n), let us analyze the behavior of each loop step-by-step:

  1. Outer Loop:
    The outer loop for (i = 1; i < n; ++i) runs exactly n−1n - 1 times.
  2. First Inner Loop:
    Inside the outer loop, p is initialized to 00. The loop for (j = n; j > 1; j = j/2) repeatedly divides jj (starting at nn) by 22 until j≤1j \le 1.
    The number of iterations is the number of times we can divide nn by 22, which is approximately log⁡2n\log_2 n. Thus, after this loop terminates:
    p≈log⁡2np \approx \log_2 n
  3. Second Inner Loop:
    The loop for (k = 1; k < p; k = k * 2) starts with k=1k = 1 and doubles kk in each iteration until k≥pk \ge p.
    The number of iterations of this loop is approximately log⁡2p\log_2 p. Since q is incremented by 11 in each iteration, the increment to q per outer loop iteration is:
    log⁡2p≈log⁡2(log⁡2n)\log_2 p \approx \log_2(\log_2 n)

Total Value of q:
Since the outer loop runs n−1n - 1 times, and each iteration increments q by log⁡2(log⁡2n)\log_2(\log_2 n) times, the final value of q returned is:
q≈(n−1)×log⁡2(log⁡2n)=Θ(nlog⁡(log⁡n))q \approx (n - 1) \times \log_2(\log_2 n) = \Theta(n \log(\log n))

Therefore, the return value is most closely approximated by nlog⁡(log⁡n)n \log(\log n).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions