sicp每日一题[1.33]

Exercise 1.33

You can obtain an even more general version of a c c u m u l a t e accumulate accumulate (Exercise 1.32) by introducing the notion of a f i l t e r filter filter on the terms to be combined. That is,combine only those terms derived from values in the range that satisfy a specified condition. The resulting f i l t e r e d − a c c u m u l a t e filtered-accumulate filteredaccumulate abstraction takes the same arguments as accumulate, together with an additional predicate of one argument that specifies the filter. Write f i l t e r e d − a c c u m u l a t e filtered-accumulate filteredaccumulate as a procedure. Show how to express the following using f i l t e r e d − a c c u m u l a t e filtered-accumulate filteredaccumulate:

  • a. the sum of the squares of the prime numbers in the interval a a a to b b b (assuming that you have a p r i m e ? prime? prime? predicate already written)
  • b. the product of all the positive integers less thann that are relatively prime to n n n (i.e., all positive integers i < n i < n i<n such that G C D ( i , n ) = 1 GCD(i, n) = 1 GCD(i,n)=1).

answer :

; recursive implementation
(define (filtered-accumulate-recur combiner null-value term a next b filter)
  (if (> a b)
      null-value
      (if (filter a)
          (combiner (term a) (filtered-accumulate-recur combiner null-value term (next a) next b filter))
          (combiner null-value (filtered-accumulate-recur combiner null-value term (next a) next b filter)))))

; for a
; computes the summation of the squares of the prime numbers in the interval a to b
(define (sum-prime-square a b)
  (filtered-accumulate-recur + 0 square a inc b prime?))

; for b
; computers the production of all the positive integers less thann that are relatively prime to n
(define (product-prime n)
  (filtered-accumulate-recur * 1 identity 1 inc n prime?))

(sum-prime-square 0 10)
(product-prime 10)
> result
87
210


; iterative implementation
(define (filtered-accumulate-iter combiner null-value term a next b filter)
  (define (iter a result)
    (if (> a b)
        result
        (if (filter a)
            (iter (next a) (combiner (term a) result))
            (iter (next a) result))))
  (iter a null-value))

; for a
; computes the summation of the squares of the prime numbers in the interval a to b
(define (sum-prime-square a b)
  (filtered-accumulate-iter + 0 square a inc b prime?))

; for b
; computers the production of all the positive integers less thann that are relatively prime to n
(define (product-prime n)
  (filtered-accumulate-iter * 1 identity 1 inc n prime?))

(sum-prime-square 0 10)
(product-prime 10)
> result
87
210
  • 15
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值