Skip to content

Latest commit

 

History

History
29 lines (21 loc) · 898 Bytes

1.25.md

File metadata and controls

29 lines (21 loc) · 898 Bytes

1.25

Question

Alyssa P. Hacker complains that we went to a lot of extra work in writing expmod. After all, she says, since we already know how to compute exponentials, we could have simply written

(define (expmod base exp m)
  (remainder (fast-expt base exp) m))

Is she correct? Would this procedure serve as well for our fast prime tester? Explain.

Answer

Alyssa's solution does not effectively distribute: the exponent (a big number) must be calculated only to be broken down by remainder.

On the other hand, the original expmod combines the two operations so large blocks of memory are not required:

(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))))