乐正

Actions speak louder than words.

Sicp-ex1-21

问题

使用smallest-divisor过程找出下面各数的最小因子:199,1999,19999.

解答

smallest-divisor (ex1-21.scm) download
1
2
3
4
5
6
7
8
9
10
11
12
13
(define (divisor? test-divisor n)
  (= (remainder n test-divisor) 0))

(define (find-divisor n test-divisor)
  (cond ((> (square test-divisor) n) n)
        ((divisor? test-divisor n) test-divisor)
        (else (find-divisor n (+ test-divisor 1)))))

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

(define (prime? n)
  (= n (smallest-divisor n)))
1
2
3
4
5
6
7
8
(smallest-divisor 199)
;Value: 199

(smallest-divisor 1999)
;Value: 1999

(smallest-divisor 19999)
;Value: 7

draft

« sicp-ex1-20 sicp-ex1-22 »

Comments