Proofs: Sliding-window exponentiation
These are the human proofs of Sliding-window exponentiation, at full length.
Sliding-window exponentiation returns x^e and uses at most t - 2 + ceil(t/k) + 2^(k-1) products full
This proof shows: correctness, termination.
Let be an element of a monoid with identity 1, let , and let have binary digits with . For write , the number formed by the digits above position ; so and .
Theorem. SLIDING-WINDOW-POWER terminates and returns . It uses at most squarings in the main loop and at most products by table entries, besides the at most products of line L1.
1. The table. Line L1 sets and for odd from 3 to . By induction on , , by associativity. It uses one squaring and products.
2. The window is well defined. At line L5, , so the set of indices with and contains and is not empty; let be its least element. Then , the number satisfies , and is odd since its last digit is . So exists.
3. The invariant. At each test of line L3, .
Proof. At the first test, and . Suppose at a test with .
- If , then , and line L4 sets to and to .
- If , let and be as in part 2 and . Then . After squarings, , and after the product with , , with set to .
In both cases the invariant holds at the next test.
4. Termination and result. Each pass through the loop decreases by at least 1, and the loop runs while , so it stops after at most passes, with , since a window never goes below index 0. By part 3, , which line L6 returns. Skipping squarings of and replacing by does not change any value, since and .
5. The counts. Let the passes that take line L5 be windows , from the top. The first window starts at , since ; while nothing is counted, so the first window costs nothing. Every later digit is squared exactly once, at line L4 or within a window, so the main loop makes squarings, where is the length of the first window, and products by table entries.
To bound , consider a window from to . If , the digits are all 0 by the choice of as the least index with a 1, so they are read at line L4 before the next window starts. Hence each window starts at least positions below the previous one: if a window starts at , the next starts at an index at most . Since the first starts at and every start is at least 0, the starts give , so . Adding part 1, the total is at most .