progress

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

All divisors of a number

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

easy basics ~10 min

Write divisors(n: int) -> list[int] returning every positive divisor of n, ascending, 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]

1 <= n <= 10^12.

Divisors come in pairs: if d divides n, so does n // d, and one of them is at most √n. So loop d while d * d <= n and record both. For a perfect square, d == n // d: add it once.

⭐ Bonus: checking every d up to n passes on small numbers; a speed test with several n near 10^12 earns a star with the √n loop.

Show hint

collect small divisors in one list and their partners 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