Cycle Detection: Floyd & Brent
Tortoise and hare, the cycle’s start and length, and Pollard’s rho.
Iterate any function on a finite set, , and some value must eventually repeat, after which the sequence cycles forever: its trace is shaped like the Greek letter . Finding the cycle with a hash set of visited values is easy; finding it while storing just two values is Floyd's tortoise and hare. The same idea factors integers (Pollard's rho, 1975), and it underlies the best known generic attack on the discrete logarithms behind elliptic-curve cryptography.
What you’ll learn
- Model iteration on a finite set as a functional graph, and define the tail length and the cycle length .
- Prove that Floyd's tortoise and hare meet within steps, and find and with extra memory.
- Describe Brent's power-of-two method, and compare the function evaluations of the two algorithms.
- Apply cycle detection to linked lists, duplicates in read-only arrays and Pollard's rho, and explain why rho's bound is a heuristic.
Every iteration ends in a cycle
A function on a finite set of elements is a functional graph: every element has exactly one outgoing arrow. Start anywhere and follow the arrows. Among two values must coincide, since there are of them, and from the first repetition on, the sequence repeats forever.
A linked list with a cycle is the special case where means "follow next": is the index of the first node on the cycle and the cycle's length. For a random function on points the birthday paradox sets the scale (Flajolet & Odlyzko, 1990): the expected tail and cycle lengths are both , and the expected number of distinct values visited, , is .
For a random function on points, about how many distinct values does the sequence visit, on average, before it first repeats?
Show the answer
1250
: the birthday paradox, not . Over 400 random functions on points, our simulation averaged , and , against the predicted 627, 627 and 1253.
Floyd's tortoise and hare
def floyd(f, x0):
t, h = f(x0), f(f(x0)) # phase 1: t = x_i and h = x_{2i}, for i = 1, 2, ...
while t != h:
t, h = f(t), f(f(h))
mu, t = 0, x0 # phase 2: restart t; both move one step at a time
while t != h:
t, h, mu = f(t), f(h), mu + 1
lam, h = 1, f(t) # phase 3: walk once around the cycle
while t != h:
h, lam = f(h), lam + 1
return mu, lamTwo stored values, whatever is. Knuth attributes the method to Robert W. Floyd (The Art of Computer Programming, vol. 2, §3.1, exercise 6); Floyd never published it as a paper. Tested against a hash-set search on random functions.
Phase 1. After steps the tortoise is at and the hare at . By the definition of and , they coincide exactly when and divides . The smallest such is , and among any consecutive integers starting from , one is a multiple of :
Phase 2. Restart the tortoise at and leave the hare at ; after more steps they are at and . Because is a multiple of , these are equal exactly when . So they first meet after steps, at the first node of the cycle:
Phase 3. From , the first return to takes exactly steps, by the definition of .
Brent's algorithm: fewer evaluations
Floyd's phase 1 evaluates three times per step: twice for the hare, and once for the tortoise, which walks over values the hare has already computed. Brent's algorithm (1980) keeps only the hare moving. The tortoise waits at a fixed position and, whenever the hare has made a power-of-two number of steps since the tortoise's last move, jumps to the hare's position:
def brent(f, x0):
power = lam = 1
t, h = x0, f(x0)
while t != h: # phase 1: finds lam directly
if power == lam: # a new power of two: teleport the tortoise
t, power, lam = h, 2 * power, 0
h, lam = f(h), lam + 1
t = h = x0 # phase 2: put h exactly lam steps ahead of t
for _ in range(lam):
h = f(h)
mu = 0
while t != h: # they meet at the cycle's first node
t, h, mu = f(t), f(h), mu + 1
return mu, lamOnce the tortoise sits on the cycle and the current window of steps is at least , the hare returns to it after exactly steps, so the counter lam is the cycle length. Phase 2 uses the fact that a pointer steps ahead meets the trailing one exactly at . Tested against a hash-set search.
| Random functions on points, 400 trials | Floyd | Brent |
|---|---|---|
| evaluations of until the cycle is detected | about 3,030 | about 1,960 |
| evaluations to find both and | about 4,870 | about 3,790 |
| worst case of the detection phase, over all | just under |
More memory buys fewer evaluations. Storing distinguished points, values with a rare property that is easy to test, such as many trailing zero bits, lets a walk recognize the cycle shortly after entering it, and lets many machines walk one huge function in parallel and notice when their walks collide (van Oorschot & Wiener, 1999). Large cryptanalytic collision searches are organized this way.
A sequence has tail length and cycle length . After how many steps of phase 1 do Floyd's tortoise and hare first meet?
- 7
- 10
- 9
- 21
Show the answer
C. 9
They meet at the smallest with and : the smallest multiple of 3 that is at least 7, which is 9. Check: the tortoise is at and the hare at , both on the cycle, and is a multiple of 3.
Applications: duplicates, generators and Pollard's rho
Finding a duplicate without extra memory. An array holds integers from to , so some value repeats; find one without modifying the array, using extra space. Read the array as a function on . No value equals 0, so nothing points to index 0 and it lies on the tail. The cycle's first node then has two predecessors, on the tail and on the cycle: two different indices holding the same value . So the entrance is a duplicated value, and Floyd's algorithm finds it in time.
def find_duplicate(a): # a holds n + 1 values from 1..n; read-only, O(1) extra space
t = h = 0
while True: # phase 1: meet inside the cycle
t, h = a[t], a[a[h]]
if t == h:
break
t = 0
while t != h: # phase 2: meet at the cycle's entrance
t, h = a[t], a[h]
return tOn the walk from index 0 is , so the cycle is entered at 3, the duplicate. Tested on thousands of random arrays.
Pseudorandom generators are functions iterated on a finite state, so every one of them is eventually periodic; cycle detection measures the period of a generator, or of a hash function iterated on its own output, without storing the sequence.
Pollard's rho (1975) factors an integer . Iterate . For an unknown prime factor of , the same sequence reduced mod is an iteration on only values, so it enters a cycle after roughly steps, long before the sequence mod does. A collision mod shows up as , so Floyd's two pointers detect it without knowing .
from math import gcd
def pollard_rho(N, c=1, x0=2): # N composite; returns a divisor of N, or N on failure
f = lambda x: (x * x + c) % N
t = h = x0
d = 1
while d == 1:
t, h = f(t), f(f(h))
d = gcd(abs(t - h), N)
return d # d == N: retry with another cFor the sequence starts , and at step 3, , since . For it finds after 27,573 steps with , the order of , where trial division would need tens of millions of divisions even by primes alone.
Key takeaways
- Iterating on a finite set traces a rho: a tail of values, then a cycle of ; for random functions on points, and are about each and about .
- Floyd's tortoise and hare meet after steps; restarting one pointer at finds , and one lap finds , all while storing two values.
- Brent's teleporting tortoise finds directly with about a third fewer evaluations on average; distinguished points trade memory for parallel collision search.
- Cycle detection finds duplicates in read-only arrays, measures generator periods and powers Pollard's rho, whose running time is a well-supported but unproved heuristic.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why do the two pointers in phase 2 of Floyd's algorithm meet exactly at the first node of the cycle?
- Because the hare moves twice as fast as the tortoise during phase 2
- Because the hare's lead is a multiple of , so exactly when , and the first such is
- Because the meeting point of phase 1 is always the first node of the cycle
- Because always equals
Show the answer
B. Because the hare's lead is a multiple of , so exactly when , and the first such is
Two positions on the sequence hold the same value exactly when both are at least and their distance is a multiple of . The distance is , a multiple of , so the pointers agree as soon as the trailing one reaches index , and not before, while it is still on the tail.
To find a duplicate in an array of values from to , Floyd's algorithm follows starting at index 0. Why index 0?
- Because index 0 always holds the duplicate
- Because no value equals 0, so index 0 lies on the tail, and then the cycle's entrance has two different predecessors holding the same value
- Because starting anywhere else makes the walk leave the array
- Because index 0 is always on the cycle
Show the answer
B. Because no value equals 0, so index 0 lies on the tail, and then the cycle's entrance has two different predecessors holding the same value
The entrance is reached from on the tail and from on the cycle: two different indices with the same value , which is therefore a duplicate. That argument needs , which starting at an index that nothing points to guarantees. Started on a cycle, the walk would have and could return a value that is not duplicated.
What does Brent's algorithm improve over Floyd's?
- It uses memory instead of
- It works for functions with several cycles reachable from
- It needs about a third fewer evaluations of on average, finds directly, and still stores only two values
- It is guaranteed to stop after exactly evaluations
Show the answer
C. It needs about a third fewer evaluations of on average, finds directly, and still stores only two values
Only the hare evaluates ; the tortoise just jumps to the hare's position at powers of two. Our simulation on random functions of points: about 1,960 evaluations to detect the cycle against about 3,030 for Floyd. Its worst case is comparable to Floyd's, about .
What is known about the running time of Pollard's rho with for finding a prime factor of ?
- It is proved to take steps in the worst case
- It is proved to take steps
- The bound is a heuristic, assuming behaves like a random function; it is well supported by experiments but not proved
- It always takes about steps, like trial division
Show the answer
C. The bound is a heuristic, assuming behaves like a random function; it is well supported by experiments but not proved
The birthday paradox gives about steps for a random function on values. Whether the quadratic map is random enough has never been proved, although the method has worked as predicted in practice for decades.
Further reading
- D. E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd ed. (Addison-Wesley, 1997), section 3.1 and section 4.5.4.
- R. P. Brent, "An improved Monte Carlo factorization algorithm," BIT 20 (1980), 176–184.
- J. M. Pollard, "A Monte Carlo method for factorization," BIT 15 (1975), 331–334.
- P. Flajolet & A. M. Odlyzko, "Random mapping statistics," Advances in Cryptology: EUROCRYPT '89, Lecture Notes in Computer Science 434 (1990).
- P. C. van Oorschot & M. J. Wiener, "Parallel collision search with cryptanalytic applications," Journal of Cryptology 12(1) (1999), 1–28.