Binary exponentiation returns x^e mod m full
This proof shows: correctness, termination, multiplications.worst.
Claim. Let x be an integer, e0≥0 an integer and m≥1 an integer. BINARY-EXP(x,e0,m) stops after ⌊lge0⌋+1 passes of the loop when e0≥1, and after none when e0=0. It returns the integer r with 0≤r<m and r≡xe0(modm). It makes ⌊lge0⌋ squarings and ν(e0) multiplications into r, where ν(e0) is the number of digits 1 in the binary form of e0.
Setup. We use the rules of congruences: if a≡a′ and c≡c′(modm), then ac≡a′c′(modm), and amodm≡a with 0≤amodm<m. Write rj,bj,ej for the values of r,b,e at the start of pass j+1 (so r0=1modm, b0=xmodm, and e0 is the input).
Invariant. At the start of each pass, and at the exit of the loop:
(I) r⋅be≡xe0(modm), and 0≤r<m and 0≤b<m.
Step 1: initialization. After lines L1 and L2, r=1modm≡1 and b=xmodm≡x, so rbe0≡1⋅xe0. Both values are results of a reduction modulo m, so they lie in 0 to m−1. This covers m=1, where r=b=0; then each integer is congruent to 0 and (I) holds trivially.
Step 2: maintenance. Assume (I) at the start of a pass, with e≥1. Write e=2q+d with q=⌊e/2⌋ and d=emod2∈{0,1}. Then be=bd⋅(b2)q.
- Line L4 sets r′=rbmodm if d=1 and leaves r′=r if d=0. In both cases r′≡rbd and 0≤r′<m.
- Line L5 sets e′=q.
- If q≥1, line L6 sets b′=b2modm≡b2, with 0≤b′<m. Then r′b′e′≡rbd(b2)q=rbe≡xe0.
- If q=0, line L6 leaves b′=b. Then b′e′=1=(b2)0, so again r′b′e′=r′≡rbd=rbd(b2)q=rbe≡xe0.
So (I) holds at the start of the next pass.
Step 3: termination. In each pass e′=⌊e/2⌋. For e≥1 with L binary digits, ⌊e/2⌋ has L−1 binary digits (and is 0 when L=1). So the number of binary digits drops by exactly 1 in each pass, and the loop stops after exactly L=⌊lge0⌋+1 passes when e0≥1. When e0=0, the test of line L3 fails at once.
Step 4: the result. At exit e=0, so (I) gives r=r⋅b0≡xe0(modm) with 0≤r<m. This r is unique, because two integers in 0 to m−1 that are congruent modulo m are equal. Line L7 returns it.
Step 5: the count of multiplications. In pass j+1 (for j=0,1,…,L−1), the value of e is ⌊e0/2j⌋, and its lowest digit is digit j of e0. Line L4 multiplies exactly when this digit is 1, so it runs ν(e0) times in total. Line L6 squares exactly when the new e is non-zero, that is in each pass except the last, so it runs L−1=⌊lge0⌋ times. ■
The count is at most 2⌊lge0⌋+1. Since ν(e0)≤L=⌊lge0⌋+1, the total ⌊lge0⌋+ν(e0) is at most 2⌊lge0⌋+1, with equality exactly when all L digits are 1, that is e0=2L−1.