sicp-solutions/ex-1.22.scm
Petar Kapriš a697f52405 Add solutions to exercises from section 1.2
To be noted: the drawing in exercise 1.14 is unfinished. I did it in a
notebook, but haven't yet had the time to put it in a txt file.
2025-02-05 13:59:25 +01:00

171 lines
2 KiB
Scheme

#lang sicp
(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))
(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))
#| BEGIN (Write your solution here) |#
(define (search-for-primes a b)
(cond ((> a b) '())
((not (even? a))
(timed-prime-test a)
(search-for-primes (+ a 2) b))
(else (search-for-primes (+ a 1) b))))
#| END |#
;;;; TESTED OUTPUT
;> (search-for-primes 1000 2000)
;
;1001
;1003
;1005
;1007
;1009 *** 1
;1011
;1013 *** 1
;1015
;1017
;1019 *** 1
;1021 *** 1
;1023
;1025
;1027
;1029
;1031 *** 2
;1033 *** 1
;1035
;1037
;1039 *** 2
;1041
;1043
;1045
;> (search-for-primes 10000 10100)
;
;10001
;10003
;10005
;10007 *** 7
;10009 *** 5
;10011
;10013
;10015
;10017
;10019
;10021
;10023
;10025
;10027
;10029
;10031
;10033
;10035
;10037 *** 4
;10039 *** 5
;10041
;10043
;10045
;10047
;10049
;10051
;10053
;10055
;10057
;10059
;10061 *** 5
;10063
;10065
;10067 *** 5
;10069 *** 4
;10071
;10073
;10075
;10077
;10079 *** 4
;10081
;10083
;10085
;10087
;10089
;10091 *** 5
;10093 *** 9
;10095
;10097
;10099 *** 7()
;> (search-for-primes 100000 100100)
;
;100001
;100003 *** 16
;100005
;100007
;100009
;100011
;100013
;100015
;100017
;100019 *** 15
;100021
;100023
;100025
;100027
;100029
;100031
;100033
;100035
;100037
;100039
;100041
;100043 *** 15
;100045
;100047
;100049 *** 17
;100051
;100053
;100055
;100057 *** 16
;100059
;100061
;100063
;100065
;100067
;100069 *** 16
;100071
;100073
;100075
;100077
;100079
;100081
;100083
;100085
;100087
;100089
;100091
;100093
;100095
;100097
;100099()