ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
n = 30
s = [True] * (n + 1)
s[0] = s[1] = False
for i in range(2, int(n ** 0.5) + 1):
    if s[i]:
        s[i * i::i] = [False] * len(s[i * i::i])
print(sum(s))
  1. A. 11
  2. B. 21
  3. C. 10
  4. D. 31

Correct answer: C. 10

The sieve marks composites from i² for i up to ⌊√30⌋ = 5, leaving the primes 2, 3, 5, 7, 11, 13, 17, 19, 23, 29: sum(s) = 10. Dropping the + 1 in the range would skip i = 5 and leave 25 marked prime (11); 21 counts the False entries and 31 is len(s).

More Python Programming questions

Exams that ask this topic