Exercise 1.16

This commit is contained in:
Correl Roush 2014-05-19 17:21:29 -04:00
parent 217e4ad3ee
commit a8e6f9f8e5

43
1-2.org
View file

@ -248,7 +248,31 @@ layout: org
procedure when `(sine a)' is evaluated?
* 1.2.4: Exponentiation
#+BEGIN_SRC scheme :tangle yes
;; ===================================================================
;; 1.2.4: Exponentiation
;; ===================================================================
(define (square x) (* x x))
(define (expt b n)
(expt-iter b n 1))
(define (expt-iter b counter product)
(if (= counter 0)
product
(expt-iter b
(- counter 1)
(* b product))))
(define (fast-expt b n)
(cond ((= n 0) 1)
((even? n) (square (fast-expt b (/ n 2))))
(else (* b (fast-expt b (- n 1))))))
(define (even? n)
(= (remainder n 2) 0))
#+END_SRC
** Exercise 1.16
Design a procedure that evolves an iterative
exponentiation process that uses successive squaring and uses a
@ -262,7 +286,22 @@ layout: org
defining an "invariant quantity" that remains unchanged from state
to state is a powerful way to think about the design of iterative
algorithms.)
----------------------------------------------------------------------
#+BEGIN_SRC scheme :tangle yes
;; -------------------------------------------------------------------
;; Exercise 1.16
;; -------------------------------------------------------------------
(define (1-16 b n)
(define (expt-iter b n a)
(cond ((= n 0) a)
((even? n) (expt-iter (square b) (/ n 2) a))
(else (expt-iter b (- n 1) (* a b)))))
(expt-iter b n 1.0))
#+END_SRC
** Exercise 1.17
The exponentiation algorithms in this section are
based on performing exponentiation by means of repeated