-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycle.py
59 lines (45 loc) · 1.29 KB
/
cycle.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# def periodicSequence(s0, a, b, m):
# # tortoise and hare algorithm
# def next(s, a, b, m):
# return (a * s + b) % m
# tortoise = next(s0, a, b, m)
# hare = next(tortoise, a, b, m)
# while tortoise != hare:
# tortoise = next(tortoise, a, b, m)
# hare = next(tortoise, a, b, m)
# mu = 0
# tortoise = s0
# while tortoise != hare:
# tortoise = next(tortoise, a, b, m)
# hare = next(hare, a, b, m)
# mu += 1
# lam = 1
# hare = next(tortoise, a, b, m)
# while tortoise != hare:
# hare = next(hare, a, b, m)
# lam += 1
# return lam
def periodicSequence(s0, a, b, m):
def f(s, a, b, m):
return (a * s + b) % m
tortoise = f(s0, a, b, m)
hare = f(f(s0, a, b, m), a, b, m)
while tortoise != hare:
tortoise = f(tortoise, a, b, m)
hare = f(f(hare, a, b, m), a, b, m)
mu = 0
tortoise = s0
while tortoise != hare:
tortoise = f(tortoise, a, b, m)
hare = f(hare, a, b, m)
mu += 1
lam = 1
hare = f(tortoise, a, b, m)
while tortoise != hare:
hare = f(hare, a, b, m)
lam += 1
return lam
def main():
print periodicSequence(11, 2, 6, 12)
if __name__ == "__main__":
main()