In computer science, cycle detection or cycle finding is the algorithmic problem of finding a cycle in a sequence of iterated function values.
For any function that maps a finite set to itself, and any initial value in, the sequence of iterated function values
x0, x1=f(x0), x2=f(x1), ..., xi=f(xi-1), ...
must eventually use the same value twice: there must be some pair of distinct indices and such that . Once this happens, the sequence must continue periodically, by repeating the same sequence of values from to . Cycle detection is the problem of finding and, given and .
Several algorithms are known for finding cycles quickly and with little memory. Robert W. Floyd's tortoise and hare algorithm moves two pointers at different speeds through the sequence of values until they both point to equal values. Alternatively, Brent's algorithm is based on the idea of exponential search. Both Floyd's and Brent's algorithms use only a constant number of memory cells, and take a number of function evaluations that is proportional to the distance from the start of the sequence to the first repetition. Several other algorithms trade off larger amounts of memory for fewer function evaluations.
The applications of cycle detection include testing the quality of pseudorandom number generators and cryptographic hash functions, computational number theory algorithms, detection of infinite loops in computer programs and periodic configurations in cellular automata, automated shape analysis of linked list data structures, and detection of deadlocks for transactions management in DBMS.
The figure shows a function that maps the set to itself. If one starts from and repeatedly applies, one sees the sequence of values
The cycle in this value sequence is .
Let be any finite set, be any function from to itself, and be any element of . For any, let . Let be the smallest index such that the value reappears infinitely often within the sequence of values, and let (the loop length) be the smallest positive integer such that . The cycle detection problem is the task of finding and .[1]
One can view the same problem graph-theoretically, by constructing a functional graph (that is, a directed graph in which each vertex has a single outgoing edge) the vertices of which are the elements of and the edges of which map an element to the corresponding function value, as shown in the figure. The set of vertices reachable from starting vertex form a subgraph with a shape resembling the Greek letter rho : a path of length from to a cycle of vertices.[2]
Generally, will not be specified as a table of values, the way it is shown in the figure above. Rather, a cycle detection algorithm may be given access either to the sequence of values, or to a subroutine for calculating . The task is to find and while examining as few values from the sequence or performing as few subroutine calls as possible. Typically, also, the space complexity of an algorithm for the cycle detection problem is of importance: we wish to solve the problem while using an amount of memory significantly smaller than it would take to store the entire sequence.
In some applications, and in particular in Pollard's rho algorithm for integer factorization, the algorithm has much more limited access to and to . In Pollard's rho algorithm, for instance, is the set of integers modulo an unknown prime factor of the number to be factorized, so even the size of is unknown to the algorithm.To allow cycle detection algorithms to be used with such limited knowledge, they may be designed based on the following capabilities. Initially, the algorithm is assumed to have in its memory an object representing a pointer to the starting value . At any step, it may perform one of three actions: it may copy any pointer it has to another object in memory, it may apply and replace any of its pointers by a pointer to the next object in the sequence, or it may apply a subroutine for determining whether two of its pointers represent equal values in the sequence. The equality test action may involve some nontrivial computation: for instance, in Pollard's rho algorithm, it is implemented by testing whether the difference between two stored values has a nontrivial greatest common divisor with the number to be factored.[2] In this context, by analogy to the pointer machine model of computation, an algorithm that only uses pointer copying, advancement within the sequence, and equality tests may be called a pointer algorithm.
If the input is given as a subroutine for calculating, the cycle detection problem may be trivially solved using only function applications, simply by computing the sequence of values and using a data structure such as a hash table to store these values and test whether each subsequent value has already been stored. However, the space complexity of this algorithm is proportional to, unnecessarily large. Additionally, to implement this method as a pointer algorithm would require applying the equality test to each pair of values, resulting in quadratic time overall. Thus, research in this area has concentrated on two goals: using less space than this naive algorithm, and finding pointer algorithms that use fewer equality tests.
Floyd's cycle-finding algorithm is a pointer algorithm that uses only two pointers, which move through the sequence at different speeds. It is also called the "tortoise and the hare algorithm", alluding to Aesop's fable of The Tortoise and the Hare.
The algorithm is named after Robert W. Floyd, who was credited with its invention by Donald Knuth.[3] However, the algorithm does not appear in Floyd's published work, and this may be a misattribution: Floyd describes algorithms for listing all simple cycles in a directed graph in a 1967 paper, but this paper does not describe the cycle-finding problem in functional graphs that is the subject of this article. In fact, Knuth's statement (in 1969), attributing it to Floyd, without citation, is the first known appearance in print, and it thus may be a folk theorem, not attributable to a single individual.[4]
The key insight in the algorithm is as follows. If there is a cycle, then, for any integers and,, where is the length of the loop to be found, is the index of the first element of the cycle, and is a whole integer representing the number of loops. Based on this, it can then be shown that for some if and only if (if in the cycle, then there exists some such that, which implies that ; and if there are some and such that, then and). Thus, the algorithm only needs to check for repeated values of this special form, one twice as far from the start of the sequence as the other, to find a period of a repetition that is a multiple of . Once is found, the algorithm retraces the sequence from its start to find the first repeated value in the sequence, using the fact that divides and therefore that . Finally, once the value of is known it is trivial to find the length of the shortest repeating cycle, by searching for the first position for which .
The algorithm thus maintains two pointers into the given sequence, one (the tortoise) at, and the other (the hare) at . At each step of the algorithm, it increases by one, moving the tortoise one step forward and the hare two steps forward in the sequence, and then compares the sequence values at these two pointers. The smallest value of for which the tortoise and hare point to equal values is the desired value .
The following Python code shows how this idea may be implemented as an algorithm.
# Find the position μ of first repetition. mu = 0 tortoise = x0 while tortoise != hare: tortoise = f(tortoise) hare = f(hare) # Hare and tortoise move at same speed mu += 1 # Find the length of the shortest cycle starting from x_μ # The hare moves one step at a time while tortoise is still. # lam is incremented until λ is found. lam = 1 hare = f(tortoise) while tortoise != hare: hare = f(hare) lam += 1 return lam, mu
This code only accesses the sequence by storing and copying pointers, function evaluations, and equality tests; therefore, it qualifies as a pointer algorithm. The algorithm uses operations of these types, and storage space.[5]
Richard P. Brent described an alternative cycle detection algorithm that, like the tortoise and hare algorithm, requires only two pointers into the sequence.[6] However, it is based on a different principle: searching for the smallest power of two that is larger than both and . For, the algorithm compares with each subsequent sequence value up to the next power of two, stopping when it finds a match. It has two advantages compared to the tortoise and hare algorithm: it finds the correct length of the cycle directly, rather than needing to search for it in a subsequent stage, and its steps involve only one evaluation of the function rather than three.[7]
The following Python code shows how this technique works in more detail.
# Find the position of the first repetition of length λ tortoise = hare = x0 for i in range(lam): # range(lam) produces a list with the values 0, 1, ..., lam-1 hare = f(hare) # The distance between the hare and tortoise is now λ.
# Next, the hare and tortoise move at same speed until they agree mu = 0 while tortoise != hare: tortoise = f(tortoise) hare = f(hare) mu += 1 return lam, mu
Like the tortoise and hare algorithm, this is a pointer algorithm that uses tests and function evaluations and storage space. It is not difficult to show that the number of function evaluations can never be higher than for Floyd's algorithm. Brent claims that, on average, his cycle finding algorithm runs around 36% more quickly than Floyd's and that it speeds up the Pollard rho algorithm by around 24%. He also performs an average case analysis for a randomized version of the algorithm in which the sequence of indices traced by the slower of the two pointers is not the powers of two themselves, but rather a randomized multiple of the powers of two. Although his main intended application was in integer factorization algorithms, Brent also discusses applications in testing pseudorandom number generators.[6]
R. W. Gosper's algorithm[8] [9] finds the period
λ
\mul
\muu
\mul+λ\sim\muh
The main feature of Gosper's algorithm is that it never backs up to reevaluate the generator function, and is economical in both space and time. It could be roughly described as a concurrent version of Brent's algorithm. While Brent's algorithm gradually increases the gap between the tortoise and hare, Gosper's algorithm uses several tortoises (several previous values are saved), which are roughly exponentially spaced. According to the note in HAKMEM item 132, this algorithm will detect repetition before the third occurrence of any value, i.e. the cycle will be iterated at most twice. This note also states that it is sufficient to store
\Theta(logλ)
\Theta(log(\mu+λ))
\mu+2λ\le232
Upon the
i
O(logi)
i
\mu+λ
\mu+2λ
O((\mu+λ) ⋅ log(\mu+λ))
\Theta(log(\mu+λ))
\Theta(log(\mu+λ))
\Omega(log2(\mu+λ))
\mu+λ
\Omega(log(\mu+λ))
A number of authors have studied techniques for cycle detection that use more memory than Floyd's and Brent's methods, but detect cycles more quickly. In general these methods store several previously-computed sequence values, and test whether each new value equals one of the previously-computed values. In order to do so quickly, they typically use a hash table or similar data structure for storing the previously-computed values, and therefore are not pointer algorithms: in particular, they usually cannot be applied to Pollard's rho algorithm. Where these methods differ is in how they determine which values to store. Following Nivasch,[10] we survey these techniques briefly.
(λ+\mu)(1+cM-1/2)
Any cycle detection algorithm that stores at most values from the input sequence must perform at least
(λ+\mu)\left(1+ | 1 |
M-1 |
\right)
Cycle detection has been used in many applications.
*print-circle*
variable, detects circular list structure and prints it compactly.