Skip to content
Official PYQ · 2003

GATE CS 2003 Q88 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

In the following CC program fragment, jj, kk, nn and TwoLog_n are integer variables, and AA is an array of integers. The variable nn is initialized to an integer ⩾3\geqslant 3, and TwoLog_n is initialized to the value of 2∗⌈log⁡2(n)⌉2^*\lceil \log_2(n) \rceil

for (k = 3;  k <= n; k++)
        A[k] = 0;
for (k = 2; k <= TwoLog_n; k++)
    for (j = k+1; j <= n; j++)
        A[j] = A[j] || (j%k);
for (j = 3; j <= n; j++)
    if (!A[j]) printf("%d", j);

The set of numbers printed by this program fragment is

Choose one option
View worked solution

Answer: D

To find the set of numbers printed by the program, let us analyze the conditions under which a number jj is printed.

  1. Initialization: The array elements A[j]A[j] are initialized to 00 for all j∈[3,n]j \in [3, n].
  2. Update Rule: The nested loops update A[j]A[j] as: A[j]=A[j]∨(j%k)A[j] = A[j] \lor (j \% k) for all k∈[2,TwoLog_n]k \in [2, \text{TwoLog\_n}] such that k<jk < j. This means A[j]A[j] becomes 11 if there is at least one kk in the range [2,min⁡(j−1,TwoLog_n)][2, \min(j-1, \text{TwoLog\_n})] that does not divide jj.
  3. Condition for Printing: For jj to be printed, we must have A[j]=0A[j] = 0 at the end, which requires jj to be divisible by all integers kk in the range [2,min⁡(j−1,TwoLog_n)][2, \min(j-1, \text{TwoLog\_n})].

Let us analyze the two possible cases for any j∈[3,n]j \in [3, n]:

  • Case 1: j−1≤TwoLog_nj - 1 \le \text{TwoLog\_n}
    Here, jj must be divisible by j−1j-1. For any j≥3j \ge 3, jj can never be divisible by j−1j-1 (since j−1>j/2j-1 > j/2). Thus, A[j]A[j] will always become 11.
  • Case 2: j−1>TwoLog_nj - 1 > \text{TwoLog\_n}
    Here, jj must be divisible by all integers from 22 up to TwoLog_n=2⌈log⁡2n⌉\text{TwoLog\_n} = 2\lceil \log_2 n \rceil. This means jj must be a multiple of the Least Common Multiple: L=LCM(2,3,…,2⌈log⁡2n⌉)L = \text{LCM}(2, 3, \dots, 2\lceil \log_2 n \rceil) Since LL grows exponentially, L>nL > n for all n≥3n \ge 3. Because j≤nj \le n, no such multiple jj can exist in the range [3,n][3, n].

Since A[j]A[j] becomes 11 for every j∈[3,n]j \in [3, n], the condition !A[j] is never met, and no numbers are printed. The printed set is empty, {}\{\}.

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

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