Data Structures & AlgorithmsHardProduct Company SDE · ICPC regional

How many integers n with 1 ≤ n ≤ 10000 have exactly four positive divisors? Count them with a divisor-count sieve.

How many integers n with 1 ≤ n ≤ 10000 have exactly four positive divisors? Count them with a divisor-count sieve.
N=10000
cnt=[0]*(N+1)
for d in range(1,N+1):
    for m in range(d,N+1,d): cnt[m]+=1
print(sum(1 for n in range(1,N+1) if cnt[n]==4))
What is printed?
  1. A. 25
  2. B. 2608
  3. C. 3863
  4. D. 1353

Correct answer: B. 2608

Numbers with exactly four divisors are p·q (distinct primes) or p³. Counting exactly-three-divisor numbers gives squares of primes, cumulative counts include numbers with fewer divisors, and stopping the range at 5000 drops half of the valid numbers.

More Coding Interview Problems questions

Exams that ask this topic