Correctness of Brent's cycle detection algorithm full
This proof shows: correctness.
Let x0 be the start value, xi+1=f(xi), and let μ≥0 and λ≥1 be the tail length and the cycle length. We use one fact about eventually periodic sequences.
Fact. For 0≤i<j, xi=xj exactly when i≥μ and λ divides j−i.
Proof of the fact. By the definition of μ and λ, xμ+λ=xμ, so xi+λ=xi for all i≥μ by applying f repeatedly, and then xi=xj when i≥μ and λ∣j−i. Conversely, let xi=xj with i<j. Then xi appears again, so i≥μ by the minimality of μ. Write j−i=qλ+r with 0≤r<λ. Since i≥μ, xi=xi+qλ, so xi+qλ=xi+qλ+r. Suppose r>0. Let s≥0 be such that m=i+qλ+s satisfies m≡μ(modλ). Applying f s times gives xm=xm+r. Since m≥μ and λ divides m−μ, xm=xμ and xm+r=xμ+r. So xμ=xμ+r with 0<r<λ, which contradicts the minimality of λ. So r=0. □
The first part (lines L1 to L6). Number the rounds k=0,1,2,…, where round k is the time during which power=2k. We claim that during round k, at each test of line L3, t=x2k−1, h=x2k−1+lam with 1≤lam≤2k, where lam is the counter of the pseudocode.
At the first test, after lines L1 and L2, k=0, t=x0=x20−1, h=x1 and lam=1, so the claim holds. Suppose that it holds at a test in round k and the test finds t=h. If lam<2k, line L6 moves h one step and adds 1 to lam, so the claim holds in round k with lam+1≤2k. If lam=2k, then h=x2k+1−1; line L5 sets t←h=x2k+1−1, power←2k+1 and lam←0, and line L6 sets h=x2k+1 and lam=1. The claim holds in round k+1.
By the fact, the test of line L3 in round k finds t=h exactly when 2k−1≥μ and λ divides lam. Let K be the least k with 2k−1≥μ and 2k≥λ. In a round k<K, either 2k−1<μ, and no test succeeds, or 2k<λ, and no lam in 1,…,2k is a multiple of λ, so again no test succeeds. Each such round runs to lam=2k and passes to round k+1. In round K, lam takes the values 1,2,… and the first multiple of λ is λ itself, which is at most 2K. So the loop stops in round K with lam=λ. In particular the loop terminates.
The second part (lines L7 to L10). After lines L7 and L8, t=x0 and h=xλ. Each pass of line L10 moves both one step and adds 1 to μ's counter, so before the test with counter value m, t=xm and h=xm+λ. By the fact, xm=xm+λ exactly when m≥μ. So the loop stops at the first m with m≥μ, which is m=μ. Line L11 returns (λ,μ).
Evaluation count. Lines L2 and L6 evaluate f once each time. At the end of the first part h=x2K−1+λ, and h has moved one step per evaluation from x0, so the first part uses 2K−1+λ evaluations. By the minimality of K, either K=0 or 2K−1<max(μ+1,λ), so 2K<2max(μ+1,λ) in both cases, since max(μ+1,λ)≥1. The second part uses λ evaluations in line L8 and 2μ in line L10. The total is less than 2max(μ+1,λ)+2λ+2μ. ■