Question

Consider functions Function 1 and Function 2 expressed in pseudocode as follows:

Function 1                              Function 2
  while n > 1 do                          for i = 1 to 100 * n do
     for i = 1 to n do                       x = x + 1;
        x = x + 1;                        end for
     end for
     n = floor(n/2);
  end while

Let f1(n)f_1(n) and f2(n)f_2(n) denote the number of times the statement "x = x + 1" is executed in Function 1 and Function 2, respectively.

Which of the following statements is/are TRUE?

Choose every correct option
Official answer and solution
Official answer
A and D
From
Official GATE 2023 answer key

Solution

Sum loop iterations for both functions and compare their asymptotic growth rates.

  1. Function 1:
    In each iteration of the while loop, the inner loop executes nn times, and then nn is halved (n←⌊n/2⌋n \leftarrow \lfloor n/2 \rfloor). The total executions of x = x + 1 is:

    f1(n)=n+⌊n/2⌋+⌊n/4⌋+⋯+1f_1(n) = n + \lfloor n/2 \rfloor + \lfloor n/4 \rfloor + \dots + 1

    This is a geometric series bounded by n≤f1(n)<2nn \le f_1(n) < 2n. Therefore, f1(n)=Θ(n)f_1(n) = \Theta(n).

  2. Function 2:
    The loop executes for i=1i = 1 to 100n100n. Hence:

    f2(n)=100n=Θ(n)f_2(n) = 100n = \Theta(n)
  3. Since both functions grow linearly with nn (f1(n)=Θ(n)f_1(n) = \Theta(n) and f2(n)=Θ(n)f_2(n) = \Theta(n)):

    • f1(n)∈Θ(f2(n))f_1(n) \in \Theta(f_2(n)) is TRUE (Statement A).
    • f1(n)∈O(f2(n))f_1(n) \in O(f_2(n)) is TRUE (Statement D).
    • Statements B (oo) and C (ω\omega) are strictly false since the ratio limits to a non-zero constant (1/100≤lim⁡f1/f2≤2/1001/100 \le \lim f_1/f_2 \le 2/100).
Final answer

Options (A, D)

Common trap

Assuming the while loop halving nn introduces a logarithmic term nlog⁡nn \log n, forgetting that the work halves in each step (n+n/2+n/4+⋯=2nn + n/2 + n/4 + \dots = 2n).

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2023 Computer Science and Information Technology (CS)
Question
54 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.