1. 程式人生 > >SICP習題解答1.9-1.19

SICP習題解答1.9-1.19

ex1.9-1.10

#lang racket

; exercise 1.9
;; 第一個是遞迴計算過程,第二個是迭代計算過程


; exercise 1.10
(define (A x y)
  (cond ((= y 0) 0)
        ((= x 0) (* 2 y))
        ((= y 1) 2)
        (else (A (- x 1) (A x (- y 1))))))
;; > (A 1 10)
;; 1024
;; > (A 2 4)
;; 65536
;; > (A 3 3)
;; 65536
;; >
(define (f n) (A 0 n)) ;; 2n
(define (g n) (A 1 n)) ;; 2^n
(define (h n) (A 2 n)) ;; 2^2..^2 (以2為底,做n次平方)

ex1.11-1.12

#lang racket

; exercise 1.11
;; 遞迴
(define (f-rec n)
  (if (< n 3)
      n
      (+ (f-rec (- n 1)) (* 2 (f-rec (- n 2))) (* 3 (f-rec (- n 3))))))
;; 迭代
(define (f-iter n)
  (if (< n 3)
      n
      (f-it 2 1 0 n)))
(define (f-it a b c n)
  (if (< n 3)
      a
      (f-it (+ a (* 2 b) (* 3 c)) a b (- n 1))))


; exercise 1.12
(define (YangHui-triangle row col)
  (cond ((or (= col 0) (= row col)) 1)
        (else (+ (YangHui-triangle (- row 1) col) (YangHui-triangle (- row 1) (- col 1))))))

ex1.14-1.9

#lang racket

; exercise 1.14
;; 空間O(n^2) 時間O(a^n) (a是硬幣種數,n是輸入值)

; exercise 1.15
;; a) p呼叫5次 (p (p (p (p (p (sine 0.05))))))
;; b) 空間和步數為對數級別:ceil(log3(10a))

; exercise 1.16
(define (fast-expt b n)
  (if (= n 0)
      1
      (iter b n 1)))
(define (iter b n k)
  (cond ((= n 1) (* b k))
        ((even? n) (iter (* b b) (/ n 2) k))
        (else (iter (* b b) (/ (- n 1) 2) (* k b)))))
(define (even? n)
  (= (remainder n 2) 0))

; exercise 1.17
(define (double n)
  (+ n n))
(define (halve n)
  (/ n 2))
(define (fast-rec-* a b)
  (cond ((= b 0) 0)
      ((even? b) (double (fast-rec-* a (halve b))))
      (else (+ a (fast-rec-* a (- b 1))))))

; exercise 1.18
(define (fast-* a b)
  (fast-*-iter a b 0))
(define (fast-*-iter a b k)
  (cond ((= b 0) k)
        ((even? b) (fast-*-iter (double a) (halve b) k))
        (else (fast-*-iter a (- b 1) (+ a k)))))

; exercise 1.19
(define (fib n) 
   (fib-iter 1 0 0 1 n)) 
 (define (fib-iter a b p q count) 
   (cond ((= count 0) b) 
         ((even? count) 
          (fib-iter a 
                    b 
                    (+ (square p) (square q)) ;; p'=p^2+q^2   q'=q^2+2pq 可以推匯出來
                    (+ (* 2 p q) (square q)) 
                    (/ count 2))) 
         (else (fib-iter (+ (* b q) (* a q) (* a p)) 
                         (+ (* b p) (* a q)) 
                         p 
                         q 
                         (- count 1))))) 
 (define (square x) (* x x))