|
|
|
|
|
by gamegoblin
3134 days ago
|
|
Consider a cycle of length n. Consider two integers, i and j that have arbitrary initial values in [0, n). We want to prove that the following loop always terminates: while i % n != j % n:
i += 1
j += 2
If we represent this as an equation over time, where t is the number of loops, we want to prove that for some t the following is true: (i + t) % n = (j + 2t) % n
Solving for t: (i % n) + (t % n) = (j % n) + (2t % n)
(i % n) - (j % n) = t % n
(i - j) % n = t % n
We can generalize for arbitrary speeds of the pointers. Let's say i moves at speed x and j moves at speed y: (i + x*t) % n = (j + y*t) % n
(i % n) + (x*t) % n = (j % n) + (y*t % n)
(i - j) % n = t*(y - x) % n
This will always have a solution if (y-x) is coprime with n.A trivial case where it doesn't work, for example, is x=2, y=4, n=any even number. Imagine if i starts on an odd number and j starts on an even number. It's clear that i will always be odd and j will always be even. Note that y-x (2 in this case) shares a prime factor (not coprime) with all even numbers. |
|
Your explanation is difficult to follow when you do distributivity of % over +. I mean when you move from
to Here I read the '=' as normal number equality. A simplified example to demostrate that distributivity is not valid here: In the second line x=5 is a solution. But in the first line x is not a solution.It's better to express your explanation using "= (mod n)" from the beginning.