Enumerate Positive Factors in Sorted Order
Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
Write a function all_divisors that takes a positive integer n and returns every positive integer factor of n in strictly increasing order.
def all_divisors(n: int) -> list[int]:
Divisor Rules
- Exact divisibility: An integer
d >= 1is a factor ofnwhenever dividingnbydleaves remainder0(n % d == 0). - Unique ascending output: Include each factor once, ordered from smallest (
1) to largest (n). Whenn == 1, the returned list is[1]. - Efficiency consideration: Once you have an
O(sqrt(n))algorithm working, consider how you would answer whether the asymptotic runtime can grow even more slowly thansqrt(n).
Examples
Example 1
Input: n = 28
Output: [1, 2, 4, 7, 14, 28]
The factor pairs (1, 28), (2, 14), and (4, 7) produce six distinct divisors in ascending order.
Example 2
Input: n = 100
Output: [1, 2, 4, 5, 10, 20, 25, 50, 100]
Because 100 = 10 * 10 is a perfect square, its square root 10 pairs with itself and is listed once rather than duplicated.
Example 3
Input: n = 53
Output: [1, 53]
Because 53 is a prime number, no integer strictly between 1 and 53 divides it evenly.
Constraints
1 <= n <= 10^12- Inputs can surpass the 32-bit signed limit (
2^31 - 1), so use 64-bit integer types in fixed-width languages (all values remain well below2^53).
Step-by-step walkthrough
Understand the goal and the scale of n
A positive integer
dis a divisor (factor) ofnwhenever dividingnbydleaves remainder0(n % d == 0). Given1 <= n <= 10^12, we want to return every positive divisor ofnin strictly increasing order without duplicates.Two observations stand out right away:
- The result always starts at
1and finishes atn(whenn = 1, those coincide, giving[1]). ncan reach1,000,000,000,000(10^12), ruling out a linear scan up tonand requiring 64-bit integers in statically typed languages.
- The result always starts at
Why checking every number up to n is too slow
A naive loop tests every candidate
dfrom1throughn:for d from 1 to n: if n % d == 0: record dAlthough this visits divisors in sorted order automatically (making it handy as a small-input test oracle), at
n = 10^12it performs one trillion modulo checks. At ~5 * 10^7loop iterations per second in Python, a single call would run for well over five hours.Key insight: divisors pair up symmetrically across sqrt(n)
Whenever
ddividesnevenly, the complementary quotientpartner = n // dis also an integer factor ofn, becaused * partner = n. Factors always arrive in pairs whose product isn:n = 100, sqrt(100) = 10 small (<= 10): 1 2 4 5 10 | | | | | v v v v v partner (>= 10): 100 50 25 20 10 (same number!)Why is testing
d <= sqrt(n)guaranteed to catch every factor? If bothdandpartnerexceededsqrt(n), their productd * partnerwould exceedsqrt(n) * sqrt(n) = n, contradictingd * partner = n. Every divisor abovesqrt(n)is therefore paired with one at or belowsqrt(n).At
n = 10^12, stopping atsqrt(n)cuts the work from10^12checks down to10^6checks — a million-fold speedup.To compute that upper bound without precision bugs, use
math.isqrt(n), which returns the integer square root (the exact integer floor ofsqrt(n)). Avoidint(n ** 0.5): 64-bit IEEE floats hold only 53 bits of significand precision and can round up by1on large integers (first failing at67,108,865^2 - 1 = 4,503,599,761,588,224, whereint(n ** 0.5)gives67,108,865instead of67,108,864).Keep ascending order without sorting
Pushing both
dandn // dinto one list on the fly scramblesn = 100into[1, 100, 2, 50, 4, 25, 5, 20, 10]. Look at the two halves separately instead:- As
dsteps upward (1, 2, 4, 5, 10), the small factors arrive in ascending order. - Simultaneously, their partners
100 // d(100, 50, 25, 20) arrive in descending order, and every partner exceeds everything insmall_divisors.
small_divisors (ascending): [1, 2, 4, 5, 10] large_divisors (descending): [100, 50, 25, 20] reverse(large_divisors): [20, 25, 50, 100] concatenated result: [1, 2, 4, 5, 10, 20, 25, 50, 100]Keeping two lists, reversing
large_divisorsonce after the loop, and returningsmall_divisors + large_divisorsproduces sorted output inO(d(n))time with zero sorting overhead.- As
Guard against duplicates on perfect squares
A perfect square equals an integer multiplied by itself, such as
100 = 10 * 10or1 = 1 * 1. Whend = 10onn = 100,partner = 100 // 10is also10. Appendingpartnerunconditionally would record10in both lists ([..., 10, 10, ...]).Guarding with
if partner != d:ensures the square root is stored once. Including+ 1inrange(1, limit + 1)is equally essential sod = limititself is checked.from math import isqrt from typing import List def all_divisors(n: int) -> list[int]: # small_divisors: divisors d <= isqrt(n) in ascending order, e.g. [1, 2, 4, 5, 10] for n = 100 small_divisors: List[int] = [] # large_divisors: matching partners n // d > isqrt(n) in descending order, e.g. [100, 50, 25, 20] large_divisors: List[int] = [] # Every divisor above sqrt(n) pairs with one at or below sqrt(n), # and math.isqrt(n) computes floor(sqrt(n)) using exact integer arithmetic. limit = isqrt(n) # Phase 1: test every candidate d from 1 up to limit inclusive (+ 1 includes limit itself). for d in range(1, limit + 1): if n % d == 0: small_divisors.append(d) partner = n // d # When n is a perfect square (such as 100 = 10 * 10 or 1 = 1 * 1), # partner equals d; skip adding it again so every divisor appears once. if partner != d: large_divisors.append(partner) # Phase 2: as d grew upward, n // d shrank downward, so reverse large_divisors # to turn descending order into ascending order without an extra sort. large_divisors.reverse() return small_divisors + large_divisorsTrace Example 1 and Example 2 step by step
First trace Example 1 (
n = 28), wherelimit = isqrt(28) = 5:d = 1:28 % 1 == 0->small = [1],large = [28]d = 2:28 % 2 == 0->small = [1, 2],large = [28, 14]d = 3:28 % 3 == 1-> skippedd = 4:28 % 4 == 0->small = [1, 2, 4],large = [28, 14, 7]d = 5:28 % 5 == 3-> skipped- Reverse
largeto[7, 14, 28]and concatenate ->[1, 2, 4, 7, 14, 28].
Now trace Example 2 (
n = 100), wherelimit = isqrt(100) = 10:d | 100 % d | partner | small_divisors | large_divisors ---+---------+---------+---------------------+--------------------- 1 | 0 | 100 | [1] | [100] 2 | 0 | 50 | [1, 2] | [100, 50] 4 | 0 | 25 | [1, 2, 4] | [100, 50, 25] 5 | 0 | 20 | [1, 2, 4, 5] | [100, 50, 25, 20] 10 | 0 | 10 | [1, 2, 4, 5, 10] | [100, 50, 25, 20] (partner == d, skipped) (candidates 3, 6, 7, 8, 9 leave non-zero remainders) After large_divisors.reverse(): [20, 25, 50, 100] Final answer: [1, 2, 4, 5, 10, 20, 25, 50, 100]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from math import isqrt def all_divisors(n: int) -> list[int]: # small_divisors: divisors d <= isqrt(n) in ascending order, e.g. [1, 2, 4, 5, 10] for n = 100 small_divisors: List[int] = [] # large_divisors: matching partners n // d > isqrt(n) in descending order, e.g. [100, 50, 25, 20] large_divisors: List[int] = [] # Every divisor above sqrt(n) pairs with one at or below sqrt(n), # and math.isqrt(n) computes floor(sqrt(n)) using exact integer arithmetic. limit = isqrt(n) # Phase 1: test every candidate d from 1 up to limit inclusive (+ 1 includes limit itself). for d in range(1, limit + 1): if n % d == 0: small_divisors.append(d) partner = n // d # When n is a perfect square (such as 100 = 10 * 10 or 1 = 1 * 1), # partner equals d; skip adding it again so every divisor appears once. if partner != d: large_divisors.append(partner) # Phase 2: as d grew upward, n // d shrank downward, so reverse large_divisors # to turn descending order into ascending order without an extra sort. large_divisors.reverse() return small_divisors + large_divisors✅ Submit now — all tests should pass.
Intuition & how it works
Imagine listing every whole-number rectangle (width, height) whose area equals n. Once width grows past sqrt(n), you stop uncovering new shapes and simply encounter sideways rotations of rectangles you already recorded (4 x 7 turned into 7 x 4 for n = 28). That symmetry guarantees that every divisor d <= sqrt(n) hands you its complementary partner n // d >= sqrt(n) automatically.
The naive approach tests every integer from 1 up to n (n % d == 0). While trivial to write, at n = 10^12 it runs one trillion modulo operations, taking hours in Python. Stopping at n // 2 still leaves 5 * 10^11 checks, whereas pairing across sqrt(n) finishes in at most 10^6 checks.
Walk through Example 1 with n = 28, where the integer square root (the exact integer floor of sqrt(n)) is isqrt(28) = 5:
d = 1:28 % 1 == 0, sosmall_divisorsrecords1andlarge_divisorsrecords28 // 1 = 28.d = 2:28 % 2 == 0, sosmall_divisorsrecords2andlarge_divisorsrecords28 // 2 = 14.d = 3:28 % 3 == 1(skipped).d = 4:28 % 4 == 0, sosmall_divisorsrecords4andlarge_divisorsrecords28 // 4 = 7.d = 5:28 % 5 == 3(skipped).- Reversing
large_divisorsturns[28, 14, 7]into[7, 14, 28], and concatenating[1, 2, 4] + [7, 14, 28]yields[1, 2, 4, 7, 14, 28]in sorted order without callingsort().
Complexity
- Time: O(sqrt(n)). The loop runs
isqrt(n)iterations (10^6steps at the upper boundn = 10^12), performing one modulo check per step, while reversing and concatenating the output lists takes O(d(n)) work whered(n) <= 2 * sqrt(n)is the divisor count. - Space: O(d(n)). Both
small_divisorsandlarge_divisorshold only actual factors ofn, and across alln <= 10^12the largest possible divisor count is6,720(attained at963,761,198,400 = 2^6 * 3^4 * 5^2 * 7 * 11 * 13 * 17 * 19 * 23).
Edge cases
n = 1:isqrt(1) = 1,d = 1givespartner = 1 == d, so1is recorded once and[1]is returned.- Prime numbers (
53, or999,999,999,989near10^12): onlyd = 1dividesn, returning[1, n]afterisqrt(n)checks. - Perfect squares (
100,49,999,983^2 = 999,966,000,289): atd = isqrt(n),partner == d, and the equality check avoids duplicating the root. - Products of twin primes (
999,959 * 999,961 = 999,920,001,599):isqrt(n)equals the smaller prime999,959on the nose, so an off-by-one loop bound misses both middle factors. - Upper limit
10^12: exceeds2^31 - 1, requiring 64-bit integers in C++, Java, or Rust (Python'sintis arbitrary-precision natively).
Common mistakes
- Stopping one step early with
range(1, isqrt(n)): skipsd = isqrt(n), dropping the square root of every perfect square and missing pairs like(2, 3)onn = 6(isqrt(6) = 2). - Appending
partnerwithout checkingpartner != d: listssqrt(n)twice on every perfect square, includingn = 1([1, 1]). - Pushing
dandn // dinto a single list without sorting: interleaves small and large factors ([1, 100, 2, 50, ...]). - Using floating-point
int(n ** 0.5)instead ofmath.isqrt(n): 64-bit floats carry only 53 significand bits, soint(n ** 0.5)can round upward on large integers (4,503,599,761,588,224produces67,108,865instead of67,108,864). - 32-bit overflow on
d * d <= n: in fixed-width languages, squaring a 32-bitintoverflows pastd = 46,340well before reaching10^6.
Alternative approaches
- Prime factorization followed by Cartesian product expansion: compute the prime factorization of
n(p1^e1 * ... * pk^ek), generate all productsp1^a1 * ... * pk^akfor0 <= ai <= ei, and sort them. If you factornvia trial division (testing candidate primes up tosqrt(n)), prime inputs still require O(sqrt(n)) work, so this beats O(sqrt(n)) only when paired with a sub-square-root factoring algorithm. - Skipping even candidates when
nis odd: an odd integer cannot have even factors, so steppingdby2(1, 3, 5, ...) halves the loop iterations on oddn, though asymptotic complexity stays O(sqrt(n)).
Follow-up questions
- Can you enumerate all divisors with an asymptotic running time that grows more slowly than O(sqrt(n))? Yes: factor
nwith a sub-square-root algorithm, expand alld(n)divisors from the prime-power exponents, and sort them in O(d(n) log d(n)) time. Practically, pair a Miller-Rabin primality test (a modular-exponentiation test that is 100% deterministic for alln < 2^64using the first 12 prime bases2..37) with Pollard's rho algorithm (a randomized cycle-detection method that extracts a factorpinO(sqrt(p))expected steps, givingO(n^(1/4))expected runtime — roughly1,000operations atn = 10^12versus1,000,000). For a deterministic worst-case bound without randomness, Lehman's method factors or proves primality inO(n^(1/3))arithmetic steps, whiled(n)grows slower thann^epsilonfor anyepsilon > 0. - Suppose you must answer 10^5 separate divisor queries where every queried integer satisfies n <= 10^7. How would you speed that up? Precompute a
smallest_prime_factortable up toN = 10^7once via a sieve (marking multiples of primes inO(N log log N)time andO(N)memory). Each query then factorsninO(log n)divisions by repeatedly dividing bysmallest_prime_factor[n], expands the prime powers, and sorts the resulting list inO(log n + d(n) log d(n))time per query instead ofO(sqrt(n)). - If you only needed the count of positive divisors rather than the full list, how would you compute it from the prime factorization? Write
n = p1^e1 * p2^e2 * ... * pk^ekand return(e1 + 1) * (e2 + 1) * ... * (ek + 1). Every positive factor chooses an exponent in0..eiindependently for each primepi; for instance,100 = 2^2 * 5^2has(2 + 1) * (2 + 1) = 9divisors without generating all nine.
Follow-up questions
- Can you enumerate all divisors with an asymptotic running time that grows more slowly than O(sqrt(n))?
- Suppose you must answer 10^5 separate divisor queries where every queried integer satisfies n <= 10^7. How would you speed that up?
- If you only needed the count of positive divisors rather than the full list, how would you compute it from the prime factorization?
Similar questions
- High-Volume Low-Latency LSTM Serving vs. Transformers
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One