Skip to content
StackDecode
Number theory & mathAnimated

Prime Factorisation

Divide out each prime factor by trial division.

Time

O(√n)

Extra space

O(log n)

Use it for

Divisors, cryptography basics.

How it works

  1. Try dividing by 2, then 3, 4, 5, … while the divisor squared is at most the number.
  2. Each time a divisor divides evenly, record it and divide it out. Because smaller factors are removed first, every recorded divisor is prime.
  3. If anything greater than 1 is left at the end, it is a prime factor too.
  4. O(√n) in the worst case.

Watch it run

Loading animation…