sicp 1.22

代码如下:

 

;素数检测
(define (prime? n)
  (= n (smallest-divisor n)))

(define (smallest-divisor n)
  (find-divisor n 2))

(define (find-divisor n test-divisor)
  (cond ((> (square test-divisor) n) n)
        ((= (remainder n test-divisor) 0) test-divisor)
        (else (find-divisor n (+ test-divisor 1)))))

(define (square x)
  (* x x))

;计时
(define (timed-prime-test n)
  (newline)
  (display n)
  (start-prime-test n (runtime)))

(define (start-prime-test n start-time)
  (if (prime? n)
      (report-prime (- (runtime) start-time))))

(define (report-prime elapsed-time)
  (display " *** ")
  (display elapsed-time))

;求m到n之间的素数
(define (search-for-primes m n)
  (cond ((> m n) (newline) (display "done"))
        ((even? m) (search-for-primes (+ m 1) n))
        ((timed-prime-test m)
        (search-for-primes (+ m 2) n))))
 

你可能感兴趣的:(SICP)