mirror of
https://github.com/correl/sicp.git
synced 2024-11-23 11:09:57 +00:00
Exercise 1.16
This commit is contained in:
parent
217e4ad3ee
commit
a8e6f9f8e5
1 changed files with 41 additions and 2 deletions
43
1-2.org
43
1-2.org
|
@ -248,7 +248,31 @@ layout: org
|
||||||
procedure when `(sine a)' is evaluated?
|
procedure when `(sine a)' is evaluated?
|
||||||
|
|
||||||
* 1.2.4: Exponentiation
|
* 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
|
** Exercise 1.16
|
||||||
Design a procedure that evolves an iterative
|
Design a procedure that evolves an iterative
|
||||||
exponentiation process that uses successive squaring and uses a
|
exponentiation process that uses successive squaring and uses a
|
||||||
|
@ -262,7 +286,22 @@ layout: org
|
||||||
defining an "invariant quantity" that remains unchanged from state
|
defining an "invariant quantity" that remains unchanged from state
|
||||||
to state is a powerful way to think about the design of iterative
|
to state is a powerful way to think about the design of iterative
|
||||||
algorithms.)
|
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
|
** Exercise 1.17
|
||||||
The exponentiation algorithms in this section are
|
The exponentiation algorithms in this section are
|
||||||
based on performing exponentiation by means of repeated
|
based on performing exponentiation by means of repeated
|
||||||
|
|
Loading…
Reference in a new issue