In the following program fragment, j, k, n, and TwoLog_n are integer variables, and A is an array of integers. The variable n is initialized to an integer >= 2, and TwoLog_n is initialized to the value of 2*floor(log_2(n)): 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] || (!(A[k]) && !(A[j/k])); The set of numbers printed by this program fragment is A. {m | m <= n_0(3) m = i!} B. {m | m <= n_0(3) m = i^2} C. {m | m <= n, m is prime} D. {}

GATE 2003 · Algorithms · Identify Function · medium

Answer: The program identifies (marks with A[j]=1) all composite numbers; the numbers remaining unmarked (A[j]=0) are exactly the primes <= n. Answer: C.

  1. Understand what A[j]=1 means: A[j] is set to 1 when there exists k such that: k divides j (integer division), A[k]=0 (k is prime/unmarked), and A[j/k]=0 (j/k is prime/unmarked). This means j has a factorization j = k*(j/k) with both factors being non-composite, i.e., j is composite.
  2. Identify what is NOT marked (A[j]=0): A prime p has no factorization p = k * m with both k,m >= 2. So no iteration will set A[p]=1. Composite numbers will have A[j]=1 eventually. Therefore the set {j : A[j]=0} = {j <= n : j is prime}, and if the program prints j where A[j]=0 (or A[j]=1 marks composites, primes remain 0), the identified set is primes <= n.