A: Because of redundant processing. The operation
(mod-expt base (/ exponent 2) modulus)
should only be done once. Use let to store an intermediate result and then square
that.
(define mod-expt
(lambda (base exponent modulus)
(define mod*
(lambda (x y)
(remainder (* x y) modulus)))
(if (= exponent 0)
1
(if (even? exponent)
(let ((x (mod-expt base (/ exponent 2) modulus)))
(mod* x x))
(mod* (mod-expt base
(- exponent 1)
modulus)
base)))))