SICP ex 1-27

本文通过Scheme语言实现了一个通用的filter-accumulate过程,用于计算特定条件下数值的累积结果。具体包括了给定范围内素数平方的累加及与指定数互质的数的乘积等数学问题。

由于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)
)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值