Data Structures & AlgorithmsVery hardICPC regional · sieve application

Problem: How many integers in [1, 100] are the product of exactly two distinct primes? Run the code.

Problem: How many integers in [1, 100] are the product of exactly two distinct primes? Run the code.
def primes_upto(n):
    s = [True] * (n + 1)
    s[0] = s[1] = False
    for i in range(2, int(n ** 0.5) + 1):
        if s[i]:
            for j in range(i * i, n + 1, i):
                s[j] = False
    return [i for i in range(n + 1) if s[i]]
P = primes_upto(100)
print(sum(1 for x in range(1, 101) for i, p in enumerate(P) for q in P[i + 1:] if p * q == x))
What is printed?
  1. A. 34
  2. B. 25
  3. C. 40
  4. D. 30

Correct answer: D. 30

Products of two distinct primes up to 100 are the 30 squarefree semiprimes; squares such as 4, 9, 25 and 49 are excluded.

More Coding Interview Problems questions

Exams that ask this topic