Learn / Maths for DSA

Prime factorisation

Trial division factorises one number in O(√n): divide out each d from 2 while d × d ≤ n, and whatever is left above 1 is prime. For many queries, precompute the smallest prime factor of every number with a sieve; then each factorisation is O(log n).

How to recognise it

  • Prime factors of one number up to about 10¹².
  • Prime factors of many numbers up to about 10⁷.
  • Counting divisors, or sums of divisors, from the factorisation.

One number

d = 2
while d × d <= n:
    while n % d == 0: record d; n = n / d
    d += 1
if n > 1: record n

Many numbers

spf[x] = smallest prime factor of x (filled by a sieve)
factor(x): while x > 1: record spf[x]; x = x / spf[x]

Common mistakes

  • Forgetting the leftover prime above √n.
  • Treating 1 as having a factor.

Problems

0 of 1 solved

Check yourself

Why can trial division stop at √n?

How does a smallest-prime-factor table factorise x?

Prime factors of 12, with repeats?