Structure and Interpretation of Computer Programs Exercises 1.33

1.22 and 1.20 borrow exercises determined prime number and Euclidean algorithm process, then the preparation process with filters filtered-accumulate.

#lang racket

(define (square x) (* x x))
(define (inc n) (+ n 1))
(define (identity x) x)
(define (add a b) (+ a b))
(define (mult a b) (* a b))
//判断质数部分
(define(smallest-divisor n)
	(find-divisor n 2))
(define(find-divisor n test-divisor)
	(cond((>(square test-divisor) n ) n)
		((divides? test-divisor n) test-divisor)
		(else(find-divisor n (+ test-divisor 1)))))
(define(divides? a b)
	(=(remainder b a) 0))
(define (prime? n)
	(= n (smallest-divisor n)))
//带过滤器的accumulate方法
(define (filtered-accumulate filter conbiner null-value term a next b)
    (if (> a b)
      null-value
      (if (filter a) (conbiner (term a)
         (filtered-accumulate filter conbiner null-value term (next a) next b))
         (filtered-accumulate filter conbiner null-value term (next a) next b))))


(define (sum-prime a b)
  (filtered-accumulate prime? add 0 identity a inc b))
//判断两个数是不是互素,最大公约数是1
(define (gcd a b)
  (if (= b 0)
  a
  (gcd b (remainder a b))))
(define (mult-coprime n)
  (define (coprime? a)
  (if (= 1 (gcd a n)) #t #f))
  (filtered-accumulate coprime? mult 1 identity 1 inc n))

(sum-prime 1 10)
(mult-coprime 7)

Here we extracted coprime determination need to use two filter parameters, so that it defines an internal mult-coprime to process, can be employed to ensure that our general procedure filtered-accumulate, because it has only one filter parameter.
The final result:

18
720
Published 27 original articles · won praise 1 · views 471

Guess you like

Origin blog.csdn.net/holybird0213/article/details/104802087
Recommended