Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count primes in [L, R] with a segmented sieve (mark multiples of small primes up to √R inside the segment).

Problem: Count primes in [L, R] with a segmented sieve (mark multiples of small primes up to √R inside the segment).
import math
def seg(L, R):
    lim = int(math.isqrt(R)); small = [p for p in range(2, lim + 1) if all(p % q for q in range(2, int(p ** 0.5) + 1))]
    mark = [True] * (R - L + 1)
    for p in small:
        start = max(p * p, (L + p - 1) // p * p)
        for m in range(start, R + 1, p): mark[m - L] = False
    return sum(1 for i, ok in enumerate(mark) if ok and i + L > 1)
print(seg(100, 200), seg(1, 30))
What is printed?
  1. A. 25 10
  2. B. 21 9
  3. C. 21 10
  4. D. 20 10

Correct answer: C. 21 10

Only primes up to √200 ≈ 14 (2, 3, 5, 7, 11, 13) are needed to sieve [100, 200]; starting at max(p², first multiple ≥ L) avoids crossing out p itself. There are 21 primes between 100 and 200 and 10 up to 30.

More Coding Interview Problems questions

Exams that ask this topic