1.33

secje posted @ 2010年7月10日 07:09 in sicp , 1484 阅读
(define (filtered-accumulate filter combiner null-value term a next b)
  (cond ((> a b) null-value)
        ((filter a)
         (combiner (term a)
                   (filtered-accumulate filter combiner null-value term (next a) next b)))
        (else (filtered-accumulate filter combiner null-value term (next a) next b))))
(define (square x) (* x x))
(define (fast-prime? n)
  (define (expmod base exp m)
    (cond ((= exp 0) 1)
          ((even? exp)
           (remainder (square (expmod base (/ exp 2) m))
                      m))
          (else
           (remainder (* (remainder base m) (expmod base (- exp 1) m))
                    m))))
  (define (fermat-test a)
    (= (expmod a n n) a))
  (define (test a)
    (cond ((= a 0) #t)
          ((fermat-test a) (fermat-test (- a 1)))
          (else #f)))
  (test (- n 1)))
(define (indentity n) n)
(define (inc n) (+ n 1))
(define (prime-add a b)
  (filtered-accumulate fast-prime? + 0 square a inc b))
(define (gcd a b)
  (if (= b 0)
      a
      (gcd b (remainder a b))))
(define (check-add n)
  (define (check m)
    (if (= (gcd m n) 1)
        #t
        #f))
  (filtered-accumulate check * 1 indentity 1 inc n))

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter