Enumerate Every Factor of a Large Integer in Sorted Order
Math & Bit ManipulationAuto-graded · 24 test casesLast updated
Produce all positive factors of an integer up to 10^12 in increasing order, handling perfect squares and large primes, and consider approaches faster than a square-root scan.
Enumerate Every Factor of a Large Integer in Sorted Order
You are given a positive integer num. Return a list containing every positive integer that divides num with no remainder, sorted from smallest to largest.
A positive integer d is a factor of num exactly when num % d == 0.
Requirements
- Each factor must appear exactly once in the result, so the list is strictly increasing.
- The first element is always
1and the last element is alwaysnum. - Perfect squares need care: the square root is its own partner and must not be listed twice.
Extension (optional thinking)
A straightforward scan up to the square root of num is enough to pass, but consider whether you can do better asymptotically, for example by working from the prime factorization of num. Note that the output itself has a size that cannot be avoided.
Constraints
1 <= num <= 10^12nummay be larger than2^31 - 1, so be careful with fixed-width integer types in other languages.- All intermediate values fit comfortably within 64-bit integers.
Examples
Example 1
Input: list_factors(36)
Output: [1, 2, 3, 4, 6, 9, 12, 18, 36]
Example 2
Input: list_factors(97)
Output: [1, 97]
Example 3
Input: list_factors(1)
Output: [1]
Hints
Hint 1
Factors pair up: if d divides num, so does num // d. One factor in every pair is at most the integer square root of num, so you only need to scan that far.
Hint 2
When d * d == num, the two partners coincide. Add that value just once, and prefer integer square root over floating-point sqrt to avoid rounding errors.
Hint 3
For something faster than a square-root scan, find the prime factorization num = p1^e1 * ... * pk^ek. Every factor is a choice of exponent between 0 and ei for each prime, so build them by multiplying out and then sort. Primality testing (Miller-Rabin) and Pollard's rho make the factoring step fast.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Baseline (square-root scan). Factors come in pairs (d, num // d), and in each pair at least one member is at most isqrt(num). Loop d from 1 to isqrt(num); whenever d divides num, put d in a "small" list and num // d in a "large" list (skipping the large one if it equals d). The answer is small followed by large reversed. For num = 10^12 this is about 10^6 iterations.
Faster approach (factor first). Write num = p1^e1 * ... * pk^ek. Every factor corresponds to choosing an exponent ai in [0, ei] for each prime. So:
- Factor
numinto primes.- Use a deterministic Miller-Rabin test (bases 2 through 37) to recognize primes; this is exact far beyond 10^12.
- Strip small primes by trial division.
- For remaining composites, use Pollard's rho to find a nontrivial factor, then recurse on both parts.
- Start with
[1]and, for each primepwith exponente, replace the list by every existing value multiplied byp^0, p^1, ..., p^e. - Sort the result.
Why it is correct
- Factoring only stops at 1 or at a certified prime, and every composite is split into two smaller proper parts (rho retries with a new constant if it returns
numitself), so the recorded primes with their multiplicities multiply back tonum. - By unique factorization, each exponent choice gives a distinct number, and every factor arises from exactly one choice. So the list has exactly the product of
(ei + 1)entries, with no duplicates. Perfect squares need no special handling. - Sorting yields strictly ascending order, starting at 1 (all exponents zero) and ending at
num(all exponents maximal).
Complexity
- Factoring: expected about
O(num^(1/4))modular steps via Pollard's rho, plusO(log num)multiplications per Miller-Rabin base. - Building factors:
O(d(num)), whered(num)is the divisor count (at most 6720 fornum <= 10^12). - Sorting:
O(d(num) log d(num)). - Space:
O(d(num)).
This grows more slowly than the square root of num, though the output size d(num) is an unavoidable lower bound. At this input limit the plain square-root scan is already fast; the factorization route matters for many queries or much larger inputs.
Reference solution
from math import gcd
_SMALL_PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
def _is_prime(n):
if n < 2:
return False
for p in _SMALL_PRIMES:
if n % p == 0:
return n == p
d, s = n - 1, 0
while d % 2 == 0:
d //= 2
s += 1
for a in _SMALL_PRIMES:
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(s - 1):
x = x * x % n
if x == n - 1:
break
else:
return False
return True
def _rho(n):
if n % 2 == 0:
return 2
c = 1
while True:
f = lambda x: (x * x + c) % n
x = y = 2
d = 1
while d == 1:
x = f(x)
y = f(f(y))
d = gcd(abs(x - y), n)
if d != n:
return d
c += 1
def _factor(n, out):
if n == 1:
return
if _is_prime(n):
out[n] = out.get(n, 0) + 1
return
for p in (2, 3, 5, 7, 11, 13):
if n % p == 0:
out[p] = out.get(p, 0) + 1
_factor(n // p, out)
return
d = _rho(n)
_factor(d, out)
_factor(n // d, out)
def list_factors(num: int) -> list[int]:
fac = {}
_factor(num, fac)
divs = [1]
for p, e in fac.items():
divs = [d * p ** k for d in divs for k in range(e + 1)]
return sorted(divs)