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

Basics: all divisors up to the square root

easy basics ~10 min

Write divisors(n: int) -> list[int] returning every positive divisor of n, in ascending order, each once.

divisors(12)   # [1, 2, 3, 4, 6, 12]
divisors(36)   # [1, 2, 3, 4, 6, 9, 12, 18, 36]
divisors(13)   # [1, 13]
divisors(1)    # [1]

Checking every d from 1 to n is far too slow when n is around 10^12. Divisors come in pairs: if d divides n, so does n // d, and one of the two is at most √n. So loop d only while d * d <= n, and record both d and n // d each time n % d == 0. Watch out for perfect squares: when d == n // d, add it only once.

Constraints: 1 <= n <= 10^12. The tests also run it on several n near 10^12.

Show hint

Collect the small divisors d <= √n in one list and their partners n // d in another, then join the small list with the reversed partner list.

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

0:00
Ctrl ' run · Ctrl ↵ submit
esc