Cycle detection: Difference between revisions

Content added Content deleted
(Added Perl example)
(Add Factor example)
Line 260: Line 260:
Start index = 2
Start index = 2
</pre>
</pre>

=={{header|Factor}}==
This is a strict translation of the Python code from the Wikipedia article. Perhaps a more idiomatic version could be added in the future, although there is value in showing how Factor's lexical variables differ from most languages. A variable binding with <code>!</code> at the end is mutable, and subsequent uses of that name followed by <code>!</code> change the value of the variable to the value at the top of the data stack.
<lang factor>USING: formatting kernel locals make math prettyprint ;

: cyclical-function ( n -- m ) dup * 1 + 255 mod ;

:: brent ( x0 quot -- λ μ )
1 dup :> ( power! λ! )
x0 :> tortoise!
x0 quot call :> hare!
[ tortoise hare = not ] [
power λ = [
hare tortoise!
power 2 * power!
0 λ!
] when
hare quot call hare!
λ 1 + λ!
] while

0 :> μ!
x0 dup tortoise! hare!
λ [ hare quot call hare! ] times
[ tortoise hare = not ] [
tortoise quot call tortoise!
hare quot call hare!
μ 1 + μ!
] while
λ μ ; inline

3 [ 20 [ dup , cyclical-function ] times ] { } make nip .
3 [ cyclical-function ] brent
"Cycle length: %d\nCycle start: %d\n" printf</lang>
{{out}}
<pre>
{ 3 10 101 2 5 26 167 95 101 2 5 26 167 95 101 2 5 26 167 95 }
Cycle length: 6
Cycle start: 2
</pre>

=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
===Brent's algorithm===
===Brent's algorithm===