Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Number Theory

Factor by Collision.

Watch the explainer

Trial division to factor a number tries every candidate up to √n — hopeless for large numbers. Pollard’s rho is a clever shortcut: iterate a pseudo-random function f(x) = x² + c (mod n) and, because there are only finitely many residues, the sequence must eventually repeat — looping back on itself into a shape like the Greek letter ρ (a tail leading into a cycle). Run two pointers at different speeds until they collide; the gcd of their difference with n is very likely a real factor. Step the tortoise and hare and watch a factor fall out.

expected O(n^¼) to find a factor · a pseudo-random walk that loops · gcd reveals the factor
f(x) = x²+c mod n

A cheap pseudo-random step whose sequence eventually cycles.

the ρ shape

The sequence has a tail then a loop — draw it and it looks like the letter ρ.

tortoise & hare

Two pointers, one stepping once and one twice, to detect the cycle (Floyd).

gcd reveals a factor

gcd(|x − y|, n) is a nontrivial factor once the runners align modulo a factor.

rho.js — two runners, one collision
Ready
Factoring n = 8051. We iterate f(x)=x²+1 mod n from x=2. A slow tortoise steps once, a fast hare twice. Each step we take gcd(|tortoise − hare|, n). Step to run.
2
tortoise
2
hare
–
gcd

How it works

Two ideas combine. First, a sequence of residues mod n is eventually periodic — it must revisit a value and then loop forever, and drawn out it forms the ρ silhouette. Floyd’s tortoise-and-hare finds that loop cheaply: run one pointer at single speed and another at double, and they’re guaranteed to meet inside the cycle without storing the whole sequence. Second — the subtle part — you don’t actually care about a collision mod n; you care about a collision mod a hidden factor p. Because p is smaller, the sequence cycles mod p much sooner. When tortoise ≡ hare (mod p) but not yet mod n, their difference is a multiple of p but not of n — so gcd(|tortoise − hare|, n) lands on p.

1

Iterate a pseudo-random map

Pick f(x) = x² + c (mod n) and a start value. Its outputs bounce around unpredictably but must eventually repeat, since there are only n possible values.

2

Run tortoise and hare

Advance a slow pointer by one step and a fast pointer by two each round. Floyd’s method guarantees they collide within the cycle, using O(1) memory.

3

Take a gcd every step

Compute d = gcd(|tortoise − hare|, n). Most steps d = 1. But once the two align modulo a hidden factor p, their difference is a multiple of p, so d becomes p — a real factor.

✓

Restart if it fails

Occasionally the pointers collide mod n first, giving d = n (no factor). Then just restart with a different constant c or start value. The expected work to find a factor is about O(n^¼).

Find a factor
~O(n^¼)
Memory
O(1)
Cycle detect
Floyd
vs trial div.
O(√n)

The code

# Pollard's rho: find a nontrivial factor of n def pollard_rho(n, c=1): f = lambda x: (x*x + c) % n x = y = 2 d = 1 while d == 1: x = f(x) # tortoise: one step y = f(f(y)) # hare: two steps d = gcd(abs(x - y), n) # a real factor once they align mod p return d if d != n else pollard_rho(n, c + 1) # retry on failure

Quick check

1. Why is the sequence f(x), f(f(x)), … guaranteed to eventually repeat?

2. Why does gcd(|x − y|, n) reveal a factor?

3. What do the tortoise and hare accomplish?

FAQ

What is Pollard's rho algorithm?

A fast, memory-light algorithm for finding a nontrivial factor of a composite. It iterates a pseudo-random f(x)=x²+c mod n (which eventually cycles) and uses tortoise-and-hare cycle detection plus a gcd to extract a factor — expected ~O(n^¼), far better than O(√n) trial division.

Why is it called 'rho'?

Because the sequence of iterated values, drawn as a path, looks like the Greek letter ρ: a tail of non-repeating values leading into a circular loop (the cycle). The tail is the run-in; the circle is the repeating cycle.

Can Pollard’s rho fail?

Yes, recoverably: sometimes the pointers collide mod n first, giving gcd = n and no factor — just restart with a different c or start value. It also can’t factor a prime, so a primality test (like Miller–Rabin) is usually run first.

How does Pollard’s rho compare to other factoring methods?

Excellent for numbers with a smallish factor and for moderate sizes (competitive programming, light cryptanalysis) at ~O(n^¼) and O(1) memory. For very large numbers with only large factors, the quadratic sieve and general number field sieve dominate; rho often peels off small factors first.

The picture: the loop hides inside the big loop

tail: x0 to x7 (mod 101) 2 5 26 71 93 65 85 55 cycle: x8 to x16, then x17 = x8 97x8 17x9 88x10 69x11 15x12 24x13 72x14 34x15 46x16 tortoise x9 and hare x18 both land on 17
Factoring n = 10403 with f(x) = x² + 1 from x = 2. Reduced mod 101 the sequence has a tail of 8 values and then a cycle of only 9. Reduced mod 10403 the cycle is 126 long, so the full values do not repeat for a long time, but mod 101 they already have. The tortoise is at x9, the hare at x18, and both are 17 mod 101.

Worked example, step by step

Factor n = 10403 (the page’s second semiprime) with f(x) = x² + 1 mod n, starting both pointers at 2. Each round the tortoise takes one step, the hare two, and we compute gcd(|x − y|, n). The last column shows both pointers reduced mod 101, a factor the algorithm never knows about.

RoundTortoise xHare y|x − y|gcd with nx / y mod 101
15262115 / 26
226598572126 / 93
367734182741171 / 85
459835312933193 / 97
539033724179165 / 88
6341898126394185 / 15
715699709814155 / 72
835313682151197 / 46
951687087191910117 / 17

Eight rounds in a row give gcd 1, and the differences (21, 572, 2741 …) look unrelated to anything. In round 9 the tortoise is 5168 and the hare is 7087. Those are different numbers, but both leave remainder 17 when divided by 101, so their difference 1919 is a multiple of 101 (1919 = 101 × 19). It is not a multiple of 103, so the gcd with 10403 lands on exactly 101, and 10403 / 101 = 103 finishes the job. Nobody ever tested whether 101 divides anything: the collision found it. That is also why the loop stopped at round 9 instead of round 126, which is the point where the pointers would have collided mod 10403 itself.

Complexity and trade-offs

CaseTimeSpaceWhy
Pollard’s rhoabout √p rounds, with p the smallest prime factor; O(n¼) worst caseO(1)Birthday collision mod p. Randomized: the bound is expected, not guaranteed.
Trial divisionO(√n)O(1)Deterministic, but tries every divisor up to the smallest factor.
Rho with batched gcdsame rounds, far fewer gcdsO(1)Multiply several differences mod n and take one gcd per batch; back up if the batch hits n.
Rho with Brent’s cycle detectionsame order, fewer evaluations of fO(1)Cuts the number of evaluations of f per round; the same collision idea.
Sub-exponential sievessub-exponential in log nlargeNeeded once the smallest factor is too big for rho; heavy memory and setup.

Measured on this page’s inputs, counting rounds for rho against divisions for trial division up to the smaller factor: 8051 took 3 rounds against 82 divisions, 10403 took 9 against 100, and 1000003 × 1000033 took 478 against 1,000,002. The gap widens because rho scales with the square root of the smaller factor while trial division scales with the factor itself. The price is that rho only finds a factor, not a prime one, can return n and need a retry, and needs a primality test beside it, since on a prime it can never succeed.

Common mistakes

  • Treating d = n as a factor

    On n = 15 with c = 2 the loop stops at round 2 with gcd 15, the whole number. With c = 1 the same input gives 3 at round 1. When d == n the pointers collided mod every prime factor at once; change c or the start value and run again.

  • Running it on a prime

    On a prime such as 97 every run ends with gcd 97 = n, because no smaller factor exists. The page’s retry-with-c + 1 code then recurses forever; in Python the run ends in a RecursionError. Test primality first (Miller–Rabin) and return the number as is.

  • Skipping small factors

    For n = 8, c = 1 through 8 all give 8 or 4 and never 2 cleanly, and n = 4 returns 4 for every c from 1 to 5. Powers of two and tiny primes defeat the random map. Strip factors like 2, 3 and 5 by trial division before calling rho.

  • Choosing c = −2

    f(x) = x² − 2 is a commonly cited bad constant. On n = 10403, c = n − 2 returns 10403 on the very first round with no factor at all, where c = 1 needed 9 rounds and found 101. Avoid −2 as the constant.

  • Overflowing the square

    In JavaScript (x * x + 1) % n with plain numbers silently loses precision once x² passes 253. For n = 1000003 × 1000033 the sequence goes wrong at round 6: Number arithmetic gives 766687757202 where exact arithmetic gives 766688367596. Use BigInt, or a mulmod routine for 64-bit integers in C-like languages.

Where this shows up

  • The cheap stage of a factoring pipeline

    General-purpose integer factoring usually strips tiny primes by trial division, tests for primality, then tries rho to peel off medium-sized factors before reaching for heavier sieve methods. Rho is attractive there because it needs almost no memory and a few lines of code.

  • Why large RSA moduli resist it

    Rho costs roughly the square root of the smallest prime factor. For a modulus made of two 1024-bit primes that is on the order of 2512 rounds, far beyond reach. It only breaks keys that were generated with a small factor,

  • Number-theory tasks and contests

    Counting divisors, computing Euler’s totient or finding multiplicative order of a 64-bit number all need the prime factorization first. Trial division to the square root is too slow for 18-digit inputs; rho with a primality test factors them quickly.

  • The same trick on other problems

    The tortoise-and-hare collision idea is also used to find discrete logarithms in a group, where a pseudo-random walk is followed until two walkers collide. The cycle detection is identical; only the map and the final algebra change.

SOLVE IT YOURSELF

Solve it: factor a number by finding a collision

Trial division to √n is hopeless past twenty digits. Pollard’s rho instead walks a pseudo-random sequence until it collides modulo a hidden factor — and finds that factor in about n^¼ steps without ever knowing what it is looking for.

YOUR TASK

Implement pollard_rho(n), which returns some non-trivial factor of a composite n, and factorize(n), which returns the full sorted list of prime factors with multiplicity.

HINTS — 6 IDEAS
  1. Iterate x → x² + c mod n. The sequence eventually cycles — drawn out, it looks like the Greek letter ρ, which is where the name comes from.
  2. Use Floyd cycle detection: advance x one step and y two, so they meet inside the cycle.
  3. Each round take gcd(|x − y|, n). If x and y have collided modulo a factor p but not modulo n, that gcd is p.
  4. The birthday paradox is what makes it fast: a collision mod p is expected after about √p ≈ n^¼ steps, even though you never test any candidate divisor.
  5. The gcd can come back as n itself — a failure. Retry with a different c; that is why the reference loops over several.
  6. For factorize, recurse on both halves and use a primality test to know when to stop. Pollard’s rho finds a factor, not a prime one.
CPython · WebAssembly

Keep going

▶  Watch it explained

Pollard's Rho: Factor a 20-Digit Number in 1.9 Milliseconds

Finished this one? 0 / 99 Algorithms done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms