Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Count primes below n with the sieve of Eratosthenes.

Problem: Count primes below n with the sieve of Eratosthenes.
def count_primes(n):
    if n < 3: return 0
    is_p = [True] * n; is_p[0] = is_p[1] = False
    i = 2
    while i * i < n:
        if is_p[i]:
            for j in range(i * i, n, i): is_p[j] = False
        i += 1
    return sum(is_p)
print(count_primes(30), count_primes(100), count_primes(2))
What is printed?
  1. A. 10 25 1
  2. B. 9 25 0
  3. C. 10 26 0
  4. D. 10 25 0

Correct answer: D. 10 25 0

Primes below 30: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 → 10; below 100 → 25. 'Below 2' has none. Crossing off from i·i is enough because smaller multiples were removed by smaller primes. O(n log log n).

More Coding Interview Problems questions

Exams that ask this topic