Cycle detection: Difference between revisions

Content added Content deleted
(Added solution for C)
(Added 11l)
Line 30: Line 30:


101,2,5,26,167,95
101,2,5,26,167,95

=={{header|11l}}==
{{trans|D}}
<lang 11l>F brent(f, x0)
Int cycle_length
V hare = x0
V power = 1
L
V tortoise = hare
L(i) 1..power
hare = f(hare)
I tortoise == hare
cycle_length = i
^L.break
power *= 2

hare = x0
L 1..cycle_length
hare = f(hare)

V cycle_start = 0
V tortoise = x0
L tortoise != hare
tortoise = f(tortoise)
hare = f(hare)
cycle_start++

print_result(x0, f, cycle_length, cycle_start)

F print_result(x0, f, len, start)
print(‘Cycle length = ’len)
print(‘Start index = ’start)
V i = x0
L 1..start
i = f(i)
V cycle = [0] * len
L 0.<len
cycle[L.index] = i
i = f(i)
print(‘Cycle: ’, end' ‘’)
print(cycle)

brent(i -> (i * i + 1) % 255, 3)</lang>
{{out}}
<pre>
Cycle length = 6
Start index = 2
Cycle: [101, 2, 5, 26, 167, 95]
</pre>


=={{header|C}}==
=={{header|C}}==