ProgrammingVery hardProduct company OA

What will be the output of the following pseudocode? (isComposite[] starts all false; ops counts every assignment inside the inner loop, even to an entry that is already true.)

What will be the output of the following pseudocode? (isComposite[] starts all false; ops counts every assignment inside the inner loop, even to an entry that is already true.)
Integer ops = 0, primes = 0
for (i = 2 to 50)
    if (not isComposite[i])
        primes = primes + 1
        for (j = i * i; j <= 50; j = j + i)
            isComposite[j] = true
            ops = ops + 1
        end for
    end if
end for
Print primes, ops
  1. A. 15 45
  2. B. 15 34
  3. C. 25 45
  4. D. 15 49

Correct answer: A. 15 45

There are 15 primes up to 50. Inner-loop work happens only for primes with p² ≤ 50: p = 2 marks 4, 6, …, 50 (24 times), p = 3 marks 9, 12, …, 48 (14), p = 5 marks 25, 30, …, 50 (6), p = 7 marks 49 (1): 24 + 14 + 6 + 1 = 45. That exceeds the 34 composites in 2..50 because numbers like 12 or 30 are crossed out by more than one prime. 25 is the number of primes below 100.

More Pseudocode and Code Tracing questions

Exams that ask this topic