Exercise 1.22

Imports: [[Chapter 1.2]] prime?

(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 p? n)
  (newline)
  (display n)
  (start-prime-test p? n (runtime)))
(define (start-prime-test p? n start-time)
  (when (p? n)
    (report-prime (- (runtime) start-time))))
(define (report-prime elapsed-time)
  (display " *** ")
  (display elapsed-time))

(define (search-for-primes p? a b)
  (define (iter a b)
    (when (<= a b)
      (timed-prime-test p? a)
      (iter (+ a 2) b)))
  (iter (if (odd? a) a (+ a 1)) b))

(string-contains?
 (capture-output (search-for-primes prime? 6 10))
 "7 *** ")
=> #t

\(A =\) time for 3 primes greater than 1,000.

; 1009 *** 4.792213439941406e-5 
; 1013 *** 4.291534423828125e-5 
; 1019 *** 4.792213439941406e-5

\(B =\) time for 3 primes greater than 10,000. \((2.3A < B < 2.8A)\)

; 10007 *** 1.1086463928222656e-4 
; 10009 *** 1.1396408081054688e-4 
; 10037 *** 1.2302398681640625e-4

\(C =\) time for 3 primes greater than 100,00. \((3.3B < D < 4.1B\)

; 100003 *** 4.010200500488281e-4 
; 100019 *** 3.6597251892089844e-4 
; 100043 *** 4.558563232421875e-4

\(D =\) time for 3 primes greater than 1,000,000. \(2.8C < D < 3.4C\)

; 1000003 *** .0013530254364013672 
; 1000033 *** .0011339187622070312 
; 1000037 *** .0013699531555175781

The data bears out the \(\Theta(\sqrt{n})\) prediction. The growth between powers of ten gets closer to \(\sqrt{10} \approx 3.16\) as \(n\) gets larger. This result is compatible with the notion that programs on the machine run in time proportional to the number of steps require for the computation.