首页 > 代码库 > SICP 1.31 1.32 1.33

SICP 1.31 1.32 1.33

解:1.31

(define (add-1 x)
  (+ x 1))

(define (product term a next b)
  (if (> a b)
      1
      (* (term a) (product term (next a) next b))))

(define (product-iter term a next b)
  (define (iter x result)
    (if (> x b)
        result
        (iter (next x) (* result (term x)))))
  (iter a 1.0))

(define (factorial n)
  (product identity 1 add-1 n))

(define (pi n)
  (define (term x)
    (define t (* x 1.0))
    (cond ((even? t) (/ (+ t 2) (+ t 1)))
          (else (/ (+ t 1) (+ t 2)))))
  (* 4.0 (product-iter term 1 add-1 n)))


1.32

(define (accumulate combiner null-value term a next b)
  (if (> a b)
      null-value
      (combiner (term a)
                (accumulate combiner null-value term (next a) next b))))

(define (accumulate-iter combiner null-value term a next b)
  (define (iter x result)
    (if (> x b)
        result
        (iter (next x) (combiner (term x) result))))
  (iter a null-value))

(define (acc-sum term a next b)
  (accumulate-iter + 0 term a next b))

(define (acc-product term a next b)
  (accumulate-iter * 1 term a next b))


1.33

(define (filtered-accumulate filter combiner null-value term a next b)
  (define t (term a))
  (define lvar (if (filter t) t null-value))
  (if (> a b)
      null-value
      (combiner lvar
                (filtered-accumulate filter combiner null-value term (next a) next b))))

(define (square x)
  (* x x))
 
(define (smallest-divisor n)
  (define (divides? a b)
    (= (remainder b a) 0))
  (define (next divisor)
    (if (= divisor 2)
        3
        (+ divisor 2)))
  (define (find-divisor n test-divisor)
    (cond ((> (square test-divisor) n) n)
          ((divides? test-divisor n) test-divisor)
          (else (find-divisor n (next test-divisor)))))
  (find-divisor n 2))
 
(define (prime? n)
  (= n (smallest-divisor n)))

(define (sum-prime a b)
  (filtered-accumulate prime? + 0 identity a add-1 b))

(define (gcd a b)
  (if (= b 0)
      a
      (gcd b (remainder a b))))

(define (co-prime-product n)
  (define (co-prime? i)
    (= 1 (gcd i n)))
  (filtered-accumulate co-prime? * 1 identity 2 add-1 n))


SICP 1.31 1.32 1.33