SICP 1.22 答案

程序写出来了,但是时间没打印,DrScheme不支持。。。

(define (smallest-divisor n)
  (find-divisor n 2))
(define (find-divisor n test-divisor)
  (cond ((> (* test-divisor 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 (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))

(define (search-for-primes n)
  (timed-prime-test n)
  (cond ((even? n) (search-for-primes (+ n 1)))
        ((not (prime? n)) (search-for-primes (+ n 2)))))

(search-for-primes 10000000000)   ;141000
(search-for-primes 100000000000)  ;515000
(search-for-primes 1000000000000) ;1641000

你可能感兴趣的:(Scheme)