ProgrammingVery hardGoldman Sachs OA · TCS Digital

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Boolean mark[2..30] = all false
Integer ops = 0, j
for (each p from 2 to 30)
    if (p * p > 30)
        break
    end if
    if (not mark[p])
        j = p * p
        while (j <= 30)
            mark[j] = true
            ops = ops + 1
            j = j + p
        end while
    end if
end for
Print ops
  1. A. 24
  2. B. 19
  3. C. 29
  4. D. 26

Correct answer: A. 24

Only primes p with p² ≤ 30 sieve: p = 2 marks 4, 6, …, 30 (14 times), p = 3 marks 9, 12, …, 30 (8 times), p = 5 marks 25 and 30 (2 times); p = 4 is skipped as already marked. ops = 24, more than the 19 composites because 12, 18, 24 and 30 are marked more than once.

More Pseudocode and Code Tracing questions

Exams that ask this topic