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?- A. 10 25 1
- B. 9 25 0
- C. 10 26 0
- 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
- Problem: Compute nCr mod p for many queries using precomputed factorials and Fermat inverses (p prime). python M = 109 + 7 N = 20 fact =…
- Problem: Find the GCD of all array elements and the LCM of a pair. cpp long long g(long long a, long long b) { return b == 0 ? a : g(b, a…
- Problem: Count trailing zeros of n! (number of factors 5). python def tz(n): c = 0 while n: n //= 5; c += n return c print(tz(25)…
- Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows. python def rev(x): s = -1 if x < 0 else 1 r =…
- Problem: Find the integer x (0 ≤ x < m) such that 3x ≡ 1 (mod 11) using the extended Euclidean algorithm. python def ext(a, b): if b == 0…
- Problem: Return the excel-style column title for a column number (1 → A, 26 → Z, 27 → AA). python def title(n): s = '' while n: n -= 1 s =…