码迷,mamicode.com
首页 > 其他好文 > 详细

1.33 (过滤累积和 求区间内所有素数之和)

时间:2017-11-25 11:16:44      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:value   lambda   des   as3   prime   fine   cond   pre   null   

(define (filtered-accumulate filter? combiner null-value term a next b)
  (define (iter a result)
    (cond ((> a b) result)
          ((filter? a) (iter (next a)
                         (combiner (term a) result)))
          (else (iter (next a)
                      result))))
  (iter a null-value))

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

(define (primes-sum a b)
  (filtered-accumulate prime?
            +
            0
            (lambda (x) x)
            a
            (lambda (x) (+ x 1))
            b))

(primes-sum 1 10)

  

1.33 (过滤累积和 求区间内所有素数之和)

标签:value   lambda   des   as3   prime   fine   cond   pre   null   

原文地址:http://www.cnblogs.com/R4mble/p/7893713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!