progress

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

Divisor counts for many numbers

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

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

⭐ Bonus: looping to sqrt(x) for each number still passes; a speed test with 10^5 numbers up to 10^6 earns a star with 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