diff --git a/1-2.org b/1-2.org index 3682849..a2f0be7 100644 --- a/1-2.org +++ b/1-2.org @@ -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