An invariant makes exponent reduction safe.
Fast exponentiation can halve an even exponent after squaring the base, while an explicit product carries the unmatched factor from each odd step.
How can the exponent shrink quickly without changing the power being computed?
- Track base, exponent, and product as complete process state
- Square the base while halving an even exponent
- Move one base factor into product on an odd step
- Preserve product times base to the exponent as an invariant
At every call, product × base^exponent equals the original requested power. If exponent is even, replacing base with its square and exponent with half preserves that quantity. If exponent is odd, multiplying product by base and subtracting one from exponent preserves it instead.
The process stops when exponent reaches zero, because the remaining power is 1 and product already contains the answer. The history program records the full state at every call so each even and odd transition can be checked directly.
(begin
(define (fast-expt base exponent product)
(cond ((= exponent 0) product)
((even? exponent)
(fast-expt (* base base)
(/ exponent 2)
product))
(else
(fast-expt base
(- exponent 1)
(* product base)))))
(fast-expt 3 13 1))- Output
- —
- Value
- —
- Diagnostic
- —
The first program returns 1594323. The second returns ((2 10 1) (4 5 1) (4 4 4) (16 2 4) (256 1 4) (256 0 1024)).
Follow the even? decision before each transition. On even steps, base squares and exponent halves; on odd steps, product absorbs base and exponent decreases by one. The recorded states cover only these exact integer inputs.
Change the program before you read the hint.
Run fast-expt for 5 to exponent 11. Before running, list whether each exponent step is odd or even.
Show one hint
An odd step subtracts one, making the next exponent even. An even step halves it.