-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathex1-22-search-primes.scm
50 lines (40 loc) · 1.38 KB
/
ex1-22-search-primes.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
; Ex. 1.22 Search for Primes
; This searches for prime numbers from a lower bound to an upper
; bound that is limited by the number of primes to be found.
(define (search-primes from how-many)
(cond ((= how-many 0)
(newline)
(display "Done"))
((even? from)
(search-primes (+ from 1) how-many))
((prime? from) ; This feels redundant...
(timed-prime-test from)
(search-primes (+ from 2) (- how-many 1)))
(else
(search-primes (+ from 2) how-many))))
; In the procedure below, applying "runtime" returns an value
; that specifies the amount of time the system has been running.
(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 1000.0)))
(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 x)
(* x x))
(define (even? n)
(= (remainder n 2) 0))