read

[CODE]
(define (filter-accumulate filter combiner null-value term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (combiner result
                                 (if (filter a)
                                     (term a)
                                     null-value)))))
  (iter a null-value))

[/CODE]

a.
앞의 연습문제에서 풀었던 prime 넘버 알아보는 프로시져를 가져오자.
[CODE]
(define (smallest-divisor n)     
  (find-divisor n 2))     
    
(define (find-divisor n test-divisor)     
  (cond ((> (square test-divisor) n) n)     
        ((divides? test-divisor n) test-divisor)     
        (else (find-divisor n (+ test-divisor 1)))))     
    
(define (divides? a b)     
  (= (remainder b a) 0))     
    
(define (prime? n)     
  (= n (smallest-divisor n)))     
    
(define (square x) (* x x))  
(define (timed-prime-test n)  
  (newline)  
  (display n)  
  (start-prime-test n (runtime)))  
(define (runtime) (current-milliseconds))  
(define (start-prime-test n start-time)  
  (if (prime? n)  
      (report-prime (- (runtime) start-time))))  
(define (report-prime elapsed-time)  
  (display " *** ")  
  (display elapsed-time))  
(define (search-for-primes rangestart)  
  (define (SFP-iter start-time n)  
    (newline)  
    (display n)  
    (if (prime? n) (report-prime (- (runtime) start-time))  
        (SFP-iter start-time (+ n 2))))  
  (if (even? rangestart) (SFP-iter (runtime) (+ rangestart 1))  
      (SFP-iter (runtime) rangestart)))  
[/CODE]

위에 정의된 prime? 를 이용하면
[CODE]
> (filter-accumulate prime?
                     (lambda (x y) (+ x y))
                     0
                     (lambda (x) (* x x))
                     1
                     (lambda (x) (+ x 1))
                     5)
39
[/CODE]

b.
[CODE]
(define (1_33 n)
  (filter-accumulate
   (lambda (x) (= 1 (gcd x n)))
   (lambda (x y) (* x y))
   1
   (lambda (x) x)
   1
   (lambda (x) (+ x 1))
   n))
[/CODE]

Blog Logo

Ki Sung Bae


Published

Image

Gsong's Blog

Developer + Entrepreneur = Entreveloper

Back to Overview