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?- A. 26
- B. 27
- C. 25
- 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
- Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP. python s = '226' dp = [1]…
- Problem: Union-find with path compression and union by rank performs m operations on n elements in what amortised time per operation?
- Problem: What is the largest rectangle area that can be formed in a histogram of heights [2, 1, 5, 6, 2, 3]? Use the stack code. python h…
- Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code…
- Problem: Consider a graph where you must find the minimum 'maximum edge' on a path from s to t (a bottleneck path). Which algorithm…
- Problem: For a segment tree with n leaves supporting range-sum queries and point updates, what is the total space needed in terms of n?