<?xml version="1.0" encoding='utf-8'?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
<wml>
<card id="card1" title="Cycle detection - Page 19 - Wikipedia">
<p>
<a accesskey="1" href="page.php?w=Cycle_detection&amp;p=18">1.Previous</a><br />
<a accesskey="3" href="page.php?w=Cycle_detection&amp;p=20">3.Next</a>
</p>
<p>sequence values at these two pointers. The smallest value of  for which the tortoise and hare point to equal values is the desired value .</p>

<p>The following <a href="page.php?w=Python_%28programming_language%29">Python</a> code shows how this idea may be implemented as an algorithm.</p>

<p><syntaxhighlight lang="python">def floyd(f, x0) -> (int, int):    """Floyd's cycle detection algorithm."""    # Main phase of algorithm: finding a repetition x_i = x_2i.    # The hare moves twice as quickly as the tortoise and    # the distance between them increases by 1 at each step.    # Eventually they will both be inside the cycle and then,    # at some point, the distance between them will be    # divisible by the period ?.    tortoise = f(x0) # f(x0) is the element/node next to x0.    hare = f(f(x0))    while tortoise != hare:        tortoise = f(tortoise)        hare = f(f(hare))      # At this point the tortoise position, ?, which is also equal    # to the distance between hare and tortoise, is divisible by    # the period ?. So hare moving in cycle one step at a time,     # and tortoise (reset to x0) moving towards the cycle, will     # intersect at the beginning of the cycle. Because the     # distance between them is constant at 2?, a multiple of ?,    # they will agree as soon as the tortoise reaches index u.</syntaxhighlight></p><p>
<a accesskey="1" href="page.php?w=Cycle_detection&amp;p=18">1.Previous</a><br />
<a accesskey="3" href="page.php?w=Cycle_detection&amp;p=20">3.Next</a>
</p>

<do type="prev" label="Search">
        <go href="search.wml"/>
</do>

</card>
</wml>
