Skip to content
Official PYQ · 2013

GATE CS 2013 Q31 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

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

Choose one option
View worked solution

Answer: B

To find the return value of the function, we need to determine the final value of the variable kk. Let's analyze the loops step-by-step:

  1. Outer Loop:
    for (i = n/2; i <= n; i++)
    The loop variable ii starts at n2\frac{n}{2} and increments by 11 until it reaches nn.
    The number of iterations of this loop is: (n−n2+1)=Θ(n)\left(n - \frac{n}{2} + 1\right) = \Theta(n)
  2. Inner Loop:
    for (j = 2; j <= n; j = j*2)
    The loop variable jj starts at 22 and doubles in each iteration (2,4,8,16,…2, 4, 8, 16, \dots).
    The number of iterations of this loop is: Θ(log⁡n)\Theta(\log n)

Total Executions of the Inner Statement:

Since the loops are nested and independent of each other's loop variables, the statement inside the inner loop is executed:

Total Executions=Θ(n)×Θ(log⁡n)=Θ(nlog⁡n)\text{Total Executions} = \Theta(n) \times \Theta(\log n) = \Theta(n \log n)

Calculating the Return Value kk:

In each execution of the inner statement, the value added to kk is n2\frac{n}{2}, which is Θ(n)\Theta(n).

Therefore, the final value of kk returned by the function is:

k=∑outer∑innern2k = \sum_{\text{outer}} \sum_{\text{inner}} \frac{n}{2} k=Θ(nlog⁡n)×Θ(n)=Θ(n2log⁡n)k = \Theta(n \log n) \times \Theta(n) = \Theta(n^2 \log n)

Thus, the return value of the function is Θ(n2log⁡n)\Theta(n^2 \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