Oh wise Lispers and Conjurers of /prog/, I, humble Nubi, seek your enlightenment. I have started reading SICP, but I'm stuck on an exercise. I have figured out how to make fast-mult into a logarithmic process, but how do I make it into a tail recursion as well as a logarithmic process? Here is my code:
; SICP exercise 1-13
; Peasant's algorithm for multiplication
; write a logarithmic iterative process for mult
(define (fast-mult a b)
(cond ((= b 0) 0)
((even? b) (double (fast-mult a (halve b))))
(else (+ a (fast-mult a (- b 1))))))
(define (double a) (+ a a))
(define (halve a) (/ a 2))
(define (fast-mult2 a b)
(fast-mult-iter a a b))
(define (fast-mult-iter a n b)
(cond ((= b 1) n)
((and (even? b) (> b 2))
(fast-mult-iter a (double n) (halve b)))
(else (fast-mult-iter a (+ a n) (- b 1)))))
There seems to be two different version of SICP; the exercises in the book that I got from the library are a lot harder than the exercises in the online version.
(define (fast-mult-iter a n b)
(cond ((= b 0) n)
((even? b) (fast-mult-iter (double a) n (halve b)))
(else (fast-mult-iter a (+ a n) (- b 1)))))
If I had read my SICP more carefully, I would have known to keep an invariant quantity that remains the same after each transformation (in this case a*b + n). Thanks >>3
Here's another one. How do I make count-change, which calculates the number of different ways you can make change out a given amount, an iterative process instead of a tree-recursive one?