Section 1.2.6 of SICP gives the following procedure:
(define (expmod base exp m)
(cond ((= exp 0) 1)
((even? exp)
(remainder (square (expmod base (/ exp 2) m))
m))
(else
(remainder (* base (expmod base (- exp 1) m))
m))))
The authors claim that it "computes the exponential of a number modulo another number". For example (expmod 5 3 n)
should return (5^3) mod n.
However, from a mathematical point of view, I just can't see how it works. As reinforced by footnote 46, it is intended to use the property that for any positive integers a, b, and n, (ab) mod n = [(a mod n)(b mod n)] mod n, but I fail to see how it is actually using it. Consider (expmod 5 3 3)
:
- First, we call
(expmod 5 3 3)
. Mathematically, this means that we're asking for (5^3) mod 3. - As the second parameter is odd, we compute
(remainder (* 5 (expmod 5 (- 3 1) 3)) 3)
i.e.(remainder (* 5 (expmod 5 2 3)) 3)
. Mathematically, this is [5 * [(5^2) mod 3]] mod 3. As the initial 5 in this expression does not have a mod 3 attached, this expression is not in the (ab) mod n = [(a mod n)(b mod n)] mod n form, so it fails to use the intended property.
So, given that this it appears to not be using the intended property, why does this algorithm work? What property of modular arithmetic have I overlooked?