由于ex1-27是对于26的改进,所以直接给出27
要求,之前的模板,其实我们可以采用filter-accumulate的更通用的模板来抽象(filter-accumulate combiner null-value predicate term a next b)
要求写出给定范围素数的平方的和,以及给定的n 给定范围内GCD(a,n)=1的积
(define (filter-accumulate combiner inti-value predicate term a next b)
(define (iter count result)
(if (= count b) result
(if (predicate count) (iter (next count) (combiner result (term count)))
(iter (next count) result)
)
)
)
(iter a inti-value)
)
(define (f x) x)
(define (plus x) (+ x 1))
(define (Gcd a b)
(define (reminder x y) (if (< x y) x (reminder (- x y) y)))
(if (= b 0) a (Gcd b (reminder a b)))
)
(define (is-prime? n times)
(define (fermat n)
(define a (+ 2 (random (- n 2) ) ) )
(define (expmod base Exp div)
(define (reminder x y) (if (< x y) x (reminder (- x y) y)))
(define (square x) (* x x) )
(define (is-even? x) (= (reminder x 2) 0))
(cond ((= Exp 0) 1)
((is-even? Exp) (reminder (square (expmod base (/ Exp 2) div) ) div ) )
(else (reminder (* base (expmod base (- Exp 1) div) ) div ) ) )
)
(= (expmod a n n) a)
)
(cond ((= times 0) #t)
((fermat n) (is-prime? n (- times 1)))
(else #f))
)
(define (prime? n) (is-prime? n 5))
(define (square x) (* x x))
(define (test a)
(= (Gcd a 17) 1)
)
(define (conditional-sum a b)
(filter-accumulate + 0 prime? square a plus b)
)
(define (conditional-product a b)
(filter-accumulate * 1 test f a plus b)
)