-
Notifications
You must be signed in to change notification settings - Fork 77
/
floyd_cycle_finding.cpp
43 lines (38 loc) · 1.06 KB
/
floyd_cycle_finding.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Time Complexity: O(mu + lambda)
Space: O(1)
mu is the smallest index i
lambda(the loop length) is the smallest positive integer such that x(mu) = x(mu + lambda).
*/
pair<int, int> floyd_cycle_finding(int (*f)(int), int x0) {
// the main phase of the algorithm, finding a repetation x(i) = x(2i). hare's speed is 2 * tortoise's
int tortoise = f(x0), hare = f(f(x0));
while( tortoise != hare ) {
tortoise = f(tortoise);
hare = f(f(hare));
}
// find the position of mu, the hare and tortoise move at the same speed
int mu = 0;
hare = tortoise;
tortoise = x0;
while( tortoise != hare ) {
tortoise = f(tortoise);
hare = f(hare);
++mu;
}
// find the length of the shortest cycle starting from x(mu), hare moves, tortoise stays
int lambda = 1;
hare = f(tortoise);
while( tortoise != hare ) {
hare = f(hare);
++lambda;
}
return make_pair(mu, lambda);
}
/*
Usage:
int f(int x) {
return (( Z * x + I ) % M);
}
pair<int, int> ans = floyd_cycle_finding(&f, L);
*/