~/problems / Number theory / Primes, divisors and GCD

Divisor counts for many numbers

medium ~20 min

Write count_divisors(xs: list[int]) -> list[int] returning, for each x in xs, the number of positive divisors of x.

With up to 10^5 numbers, each up to 10^6, looping to sqrt(x) for every query is too slow in Python. Aim for one near-linear precomputation up to max(xs), then about O(log x) per number.

count_divisors([16, 17, 18])   # [5, 2, 6]
count_divisors([1])            # [1]
count_divisors([720720])       # [240]

Constraints: 1 ≤ len(xs) ≤ 10^5, 1 ≤ x ≤ 10^6.

Show hint

If x = p1^e1 · p2^e2 · ..., the divisor count is (e1 + 1)(e2 + 1).... Precompute each number's smallest prime factor with a sieve, and every x factors in O(log x) divisions.

Topic: Primes, divisors and GCD. Sieve, trial division to sqrt(n), Euclid's algorithm.

0:00
Ctrl ' run · Ctrl ↵ submit
esc