Note: this wiki is now retired and will no longer be updated!

The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.

SICP exercise 1.21

From Drewiki
Jump to: navigation, search

Problem

Use the smallest-divisor procedure from the text to find the smallest divisor of each of the following numbers: 199, 1999, 19999.

Solution

This exercise is straightforward. Here's the smallest-divisor procedure (and its dependencies) from the text:

(define (square x)
  (* x x))
 
(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))

And here are the requested answers:

(smallest-divisor 199)

Output:

199


(smallest-divisor 1999)

Output:

1999


(smallest-divisor 19999)

Output:

7
Personal tools