Mar 22, 2008

SICP Exercise 1.22

A procedure that checks a prime number.

(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)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (square n)
(* n n))


A procedure that measures the time for "prime?".
I rewrite a bit.

(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))
#f))
(define (report-prime elapsed-time)
(display " *** ")
(display elapsed-time)
#t)


DrScheme doesn't have "runtime".

(define (runtime)
(current-milliseconds))


My answer.

(define (search-for-primes min max cnt)
(cond ((> min max))
((= cnt 3))
((even? min) (search-for-primes (+ min 1) max cnt))
(else
(if (timed-prime-test min)
(search-for-primes (+ min 2) max (+ cnt 1))
(search-for-primes (+ min 2) max cnt)))))



(search-for-primes 1000 9999 0)
(search-for-primes 10000 99999 0)
(search-for-primes 100000 999999 0)
(search-for-primes 1000000 9999999 0)


It's impossible to measure the time.

No comments: