No, the function doesn't work well. Copy a fresh definition of the procedure, run it again and you'll see the error:
(define (iter b a n)
(cond ((= b 0) n)
((even? b)
(iter (/ b 2) (* 2 a) n))
(else
(iter (- b 1) (/ (* a b) (- b 1)) (+ a (* a (- b 1)))))))
(define (mul b a)
(iter b a 1))
(mul 2 3)
=> /: division by zero
In fact, the expected solution would be more along these lines, and notice that special care must be taken in case that b
is negative:
(define (iter a b n)
(cond ((zero? b) n)
((even? b)
(iter (+ a a) (/ b 2) n))
(else
(iter a (- b 1) (+ a n)))))
(define (mul a b)
(if (< b 0)
(- (iter a (- b) 0))
(iter a b 0)))
And following your example, here's how the parameters look in each iteration when we execute (mul 2 3)
:
a b n
begin: 2 3 0
1 : 2 2 2
2 : 4 1 2
3 : 4 0 6