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 >= 1 is a factor of n whenever dividing n by d leaves remainder 0 (n % d == 0).
  • Unique ascending output: Include each factor once, ordered from smallest (1) to largest (n). When n == 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 than sqrt(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 below 2^53).

Step-by-step walkthrough

  1. Understand the goal and the scale of n

    A positive integer d is a divisor (factor) of n whenever dividing n by d leaves remainder 0 (n % d == 0). Given 1 <= n <= 10^12, we want to return every positive divisor of n in strictly increasing order without duplicates.

    Two observations stand out right away:

    • The result always starts at 1 and finishes at n (when n = 1, those coincide, giving [1]).
    • n can reach 1,000,000,000,000 (10^12), ruling out a linear scan up to n and requiring 64-bit integers in statically typed languages.
  2. Why checking every number up to n is too slow

    A naive loop tests every candidate d from 1 through n:

    for d from 1 to n:
        if n % d == 0:
            record d
    

    Although this visits divisors in sorted order automatically (making it handy as a small-input test oracle), at n = 10^12 it performs one trillion modulo checks. At ~5 * 10^7 loop iterations per second in Python, a single call would run for well over five hours.

  3. Key insight: divisors pair up symmetrically across sqrt(n)

    Whenever d divides n evenly, the complementary quotient partner = n // d is also an integer factor of n, because d * partner = n. Factors always arrive in pairs whose product is n:

    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 both d and partner exceeded sqrt(n), their product d * partner would exceed sqrt(n) * sqrt(n) = n, contradicting d * partner = n. Every divisor above sqrt(n) is therefore paired with one at or below sqrt(n).

    At n = 10^12, stopping at sqrt(n) cuts the work from 10^12 checks down to 10^6 checks — 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 of sqrt(n)). Avoid int(n ** 0.5): 64-bit IEEE floats hold only 53 bits of significand precision and can round up by 1 on large integers (first failing at 67,108,865^2 - 1 = 4,503,599,761,588,224, where int(n ** 0.5) gives 67,108,865 instead of 67,108,864).

  4. Keep ascending order without sorting

    Pushing both d and n // d into one list on the fly scrambles n = 100 into [1, 100, 2, 50, 4, 25, 5, 20, 10]. Look at the two halves separately instead:

    • As d steps 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 in small_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_divisors once after the loop, and returning small_divisors + large_divisors produces sorted output in O(d(n)) time with zero sorting overhead.

  5. Guard against duplicates on perfect squares

    A perfect square equals an integer multiplied by itself, such as 100 = 10 * 10 or 1 = 1 * 1. When d = 10 on n = 100, partner = 100 // 10 is also 10. Appending partner unconditionally would record 10 in both lists ([..., 10, 10, ...]).

    Guarding with if partner != d: ensures the square root is stored once. Including + 1 in range(1, limit + 1) is equally essential so d = limit itself 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_divisors
    
  6. Trace Example 1 and Example 2 step by step

    First trace Example 1 (n = 28), where limit = 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 -> skipped
    • d = 4: 28 % 4 == 0 -> small = [1, 2, 4], large = [28, 14, 7]
    • d = 5: 28 % 5 == 3 -> skipped
    • Reverse large to [7, 14, 28] and concatenate -> [1, 2, 4, 7, 14, 28].

    Now trace Example 2 (n = 100), where limit = 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]
    
  7. 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, so small_divisors records 1 and large_divisors records 28 // 1 = 28.
  • d = 2: 28 % 2 == 0, so small_divisors records 2 and large_divisors records 28 // 2 = 14.
  • d = 3: 28 % 3 == 1 (skipped).
  • d = 4: 28 % 4 == 0, so small_divisors records 4 and large_divisors records 28 // 4 = 7.
  • d = 5: 28 % 5 == 3 (skipped).
  • Reversing large_divisors turns [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 calling sort().

Complexity

  • Time: O(sqrt(n)). The loop runs isqrt(n) iterations (10^6 steps at the upper bound n = 10^12), performing one modulo check per step, while reversing and concatenating the output lists takes O(d(n)) work where d(n) <= 2 * sqrt(n) is the divisor count.
  • Space: O(d(n)). Both small_divisors and large_divisors hold only actual factors of n, and across all n <= 10^12 the largest possible divisor count is 6,720 (attained at 963,761,198,400 = 2^6 * 3^4 * 5^2 * 7 * 11 * 13 * 17 * 19 * 23).

Edge cases

  • n = 1: isqrt(1) = 1, d = 1 gives partner = 1 == d, so 1 is recorded once and [1] is returned.
  • Prime numbers (53, or 999,999,999,989 near 10^12): only d = 1 divides n, returning [1, n] after isqrt(n) checks.
  • Perfect squares (100, 49, 999,983^2 = 999,966,000,289): at d = 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 prime 999,959 on the nose, so an off-by-one loop bound misses both middle factors.
  • Upper limit 10^12: exceeds 2^31 - 1, requiring 64-bit integers in C++, Java, or Rust (Python's int is arbitrary-precision natively).

Common mistakes

  • Stopping one step early with range(1, isqrt(n)): skips d = isqrt(n), dropping the square root of every perfect square and missing pairs like (2, 3) on n = 6 (isqrt(6) = 2).
  • Appending partner without checking partner != d: lists sqrt(n) twice on every perfect square, including n = 1 ([1, 1]).
  • Pushing d and n // d into a single list without sorting: interleaves small and large factors ([1, 100, 2, 50, ...]).
  • Using floating-point int(n ** 0.5) instead of math.isqrt(n): 64-bit floats carry only 53 significand bits, so int(n ** 0.5) can round upward on large integers (4,503,599,761,588,224 produces 67,108,865 instead of 67,108,864).
  • 32-bit overflow on d * d <= n: in fixed-width languages, squaring a 32-bit int overflows past d = 46,340 well before reaching 10^6.

Alternative approaches

  • Prime factorization followed by Cartesian product expansion: compute the prime factorization of n (p1^e1 * ... * pk^ek), generate all products p1^a1 * ... * pk^ak for 0 <= ai <= ei, and sort them. If you factor n via trial division (testing candidate primes up to sqrt(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 n is odd: an odd integer cannot have even factors, so stepping d by 2 (1, 3, 5, ...) halves the loop iterations on odd n, 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 n with a sub-square-root algorithm, expand all d(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 all n < 2^64 using the first 12 prime bases 2..37) with Pollard's rho algorithm (a randomized cycle-detection method that extracts a factor p in O(sqrt(p)) expected steps, giving O(n^(1/4)) expected runtime — roughly 1,000 operations at n = 10^12 versus 1,000,000). For a deterministic worst-case bound without randomness, Lehman's method factors or proves primality in O(n^(1/3)) arithmetic steps, while d(n) grows slower than n^epsilon for any epsilon > 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_factor table up to N = 10^7 once via a sieve (marking multiples of primes in O(N log log N) time and O(N) memory). Each query then factors n in O(log n) divisions by repeatedly dividing by smallest_prime_factor[n], expands the prime powers, and sorts the resulting list in O(log n + d(n) log d(n)) time per query instead of O(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^ek and return (e1 + 1) * (e2 + 1) * ... * (ek + 1). Every positive factor chooses an exponent in 0..ei independently for each prime pi; for instance, 100 = 2^2 * 5^2 has (2 + 1) * (2 + 1) = 9 divisors without generating all nine.

Follow-up questions

Similar questions

More PDT Partners interview questions

All 2 PDT Partners questions →