Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many twin prime pairs (p, p + 2), both prime, have p + 2 below 10000? Run the sieve.

Problem: How many twin prime pairs (p, p + 2), both prime, have p + 2 below 10000? Run the sieve.
N = 10000
s = [True] * (N + 1)
s[0] = s[1] = False
for i in range(2, 101):
    if s[i]:
        for j in range(i * i, N + 1, i):
            s[j] = False
print(sum(1 for k in range(2, N - 1) if s[k] and s[k + 2]))
What is printed?
  1. A. 206
  2. B. 205
  3. C. 204
  4. D. 210

Correct answer: B. 205

A sieve up to 10000 followed by a scan for p and p + 2 both prime gives 205 twin pairs.

More Coding Interview Problems questions

Exams that ask this topic