Data Structures & AlgorithmsModerateTCS NQT · number theory

Problem: How many primes are there up to 100? Run the sieve.

Problem: How many primes are there up to 100? Run the sieve.
n = 100
sieve = [True] * (n + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(n ** 0.5) + 1):
    if sieve[i]:
        for j in range(i * i, n + 1, i):
            sieve[j] = False
print(sum(sieve))
What is printed?
  1. A. 26
  2. B. 27
  3. C. 25
  4. D. 74

Correct answer: C. 25

The sieve leaves 25 primes from 2 to 97. Using range(i * i, n, i) never marks 100 and gives 26, forgetting to clear 0 and 1 gives 27, and counting the entries the sieve clears (the composites 4..100) gives 74. Starting the inner loop at i * i is safe because smaller multiples were already marked.

More Coding Interview Problems questions

Exams that ask this topic