Prime Factorisation — 10^9 Calls Killed API
A batch of 10^9 trial divisions requires ~3×10^13 iterations — 3.
- Prime factorization breaks numbers into unique primes: 360 = 2³ × 3² × 5
- Tau(n) = ∏(exponent+1) gives divisor count; sigma(n) = ∏(p^(a+1)-1)/(p-1) gives sum
- Trial division O(√n) per number – fine for n ≤ 10¹², deadly above
- SPF sieve drops per-number cost to O(log n) after O(n log log n) preprocessing
- Pollard's rho factors composite numbers up to 10¹⁸ in seconds – but has failure modes
Every integer > 1 is either prime or can be broken down into a unique product of primes — like 360 = 2³ × 3² × 5. This is the Fundamental Theorem of Arithmetic. Factorizing a number unlocks many properties: number of divisors, sum of divisors, Euler's totient, and more. The speed of factorization depends heavily on the algorithm chosen.
RSA's security depends on one fact: factoring the product of two large primes is computationally hard. The best known classical algorithm (General Number Field Sieve) runs in sub-exponential but super-polynomial time. A 2048-bit RSA modulus would take longer than the age of the universe to factor on current hardware.
For small numbers — up to ~10^12 — trial division works fine. For competitive programming — up to ~10^6 per query — the SPF sieve turns factorization from O(√n) per query to O(log n). Knowing which regime you're in and choosing the right tool is the practical skill.
The real trap? Assuming one algorithm works for all sizes. Engineers waste hours because they don't detect when trial division becomes impractical or when Pollard's rho loops indefinitely on a prime input.
Trial Division
Check divisibility by all primes up to √n. O(√n) per number. This is the simplest and most intuitive algorithm. For a single n ≤ 10^12, trial division completes in microseconds. But scale it to 10^6 numbers and you're looking at days.
The key optimization: after checking 2, only check odd numbers. That halves the work. For even better performance, precompute a list of primes up to √max_n using a simple sieve, then only divide by those primes.
Number of Divisors and Sum of Divisors
- Number of divisors: τ(n) = (a1+1)(a2+1)...(ak+1)
- Sum of divisors: σ(n) = Π (p^(a+1)
- 1) / (p
- 1)
- Euler's totient: φ(n) = n × Π (1
- 1/p) for each prime p dividing n
These formulas are direct consequences of the multiplicative property. For example, τ(360) = τ(2³)τ(3²)τ(5¹) = (3+1)(2+1)(1+1) = 4×3×2 = 24 divisors. The sum σ(360) = (2^(3+1)-1)/(2-1) × (3^(2+1)-1)/(3-1) × (5^(1+1)-1)/(5-1) = (16-1)/1 × (27-1)/2 × (25-1)/4 = 15 × 13 × 6 = 1170.
Listing All Divisors
To list all divisors, iterate up to √n and collect pairs. Complexity O(√n) – but you can't beat that because output size is O(τ(n)) which is at most O(√n). For n=10^12, τ(n) is at most ~6720, so enumerating divisors is feasible.
The algorithm: for each divisor d ≤ √n, if n % d == 0, add d and n//d. Sort the result at the end.
SPF Sieve for Batch Factorization
When factorizing many numbers up to n, precompute the Smallest Prime Factor (SPF) sieve. Each factorization then takes O(log n) instead of O(√n).
Construction: Create an array spf[0..n] filled with 0. For i from 2 to n, if spf[i]==0 (i is prime), set spf[i]=i and for j in range(i*i, n+1, i), if spf[j]==0, set spf[j]=i. Then to factor a number x, repeatedly divide by spf[x] and record the count.
This is the standard for competitive programming and any scenario where you need to factorise a batch of numbers up to ~10^7.
Pollard's Rho Algorithm for Large Composite Numbers
When n exceeds ~10^12 and you need to factorise a single number, trial division becomes impractical. Pollard's rho is a probabilistic algorithm that finds a non-trivial factor in O(n^(1/4)) expected time.
It works by iterating a pseudo-random function f(x) = (x^2 + c) mod n and detecting cycles using Floyd's cycle detection. When a cycle is found, gcd(|x-y|, n) gives a factor.
It's not guaranteed – for prime n it will loop forever. Always pair it with a primality test (Miller-Rabin) before running rho.
- The function f(x) = x^2 + c mod n produces a sequence that must eventually repeat.
- Once it repeats, the difference between two pointers (tortoise and hare) often shares a factor with n.
- If the sequence repeats without hitting a factor, change c and restart.
- Expected number of steps before finding a factor is O(√p) where p is the smallest prime factor.
10^9 Calls to trial_division() Collapsed the API
- Always compute total work (calls × cost per call) before committing to an algorithm.
- Trial division is for single queries, not batch processing.
- When the input range is ≤ 10^6 per query, use SPF sieve. For larger single numbers (>10^12), use Pollard's rho.
Key takeaways
Common mistakes to avoid
3 patternsUsing trial division in a loop without early exit on prime
Forgetting to add the final prime factor after trial division loop
if n > 1: factors[n] = factors.get(n, 0) + 1 after the loop.Assuming Pollard's rho works on prime numbers
Interview Questions on This Topic
How many divisors does 10^6 have? How do you compute this from its factorization?
Frequently Asked Questions
That's Number Theory. Mark it forged?
3 min read · try the examples if you haven't