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?- A. 25 10
- B. 21 9
- C. 21 10
- 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
- Edge case: itertools.groupby on unsorted data. python from itertools import groupby data = "aabbbaacc" print([(k, len(list(g))) for k, g…
- Problem: Row n of Pascal's triangle built in place, plus two checks. python def row(n): r = [1] for in range(n): r = [1] + [r[i] + r[i+1]…
- Problem: Find the maximum sum of a sub-rectangle whose sum does not exceed k (fix two columns, then 'max subarray sum ≤ k' with a sorted…
- Problem: What does the following print? It is the multiplicative inverse of 7 modulo 26. python print(pow(7, -1, 26))
- Problem: How many trailing zeros does 100! have? Run the code that counts factors of 5. python n = 100 c = 0 p = 5 while p <= n: c += n //…
- Problem: Starting from 27, the Collatz map is n -> n/2 if n is even and n -> 3n+1 if n is odd. How many steps does it take to first reach…