learning-sicp

My embarrassing half assed SICP run.
git clone https://kaka.farm/~git/learning-sicp
Log | Files | Refs

exercise-23.scm (1779B)


      1 
      2 ;; Exercise 1.23
      3 
      4 (define (next test-divisor)
      5   (if (= test-divisor 2)
      6       3
      7       (+ test-divisor 2)))
      8 
      9 (define (smallest-divisor n)
     10   (find-divisor n 2))
     11 
     12 (define (find-divisor n test-divisor)
     13   (cond
     14    ((> (square test-divisor) n)
     15     n)
     16 
     17    ((divides? test-divisor n)
     18     test-divisor)
     19 
     20    (else (find-divisor n (next test-divisor)))))
     21 
     22 (test-begin "prime-1.23")
     23 (test-equal '(#t #f #t #f #t #f) (map (cut divides? 2 <>) '(2 3 4 5 6 7)))
     24 (test-equal '(2 3 2 5 2 7) (map smallest-divisor '(2 3 4 5 6 7)))
     25 (test-equal '(#t #t #f #t #f #t) (map prime? '(2 3 4 5 6 7)))
     26 (test-end "prime-1.23")
     27 
     28 (run-delay-if-full-flag
     29  (delay
     30    (let ((port (open-output-file "primes-half.txt")))
     31 
     32      (define (runtime)
     33        (time-nanosecond (current-time time-process)))
     34 
     35      (define (display x)
     36        (format port "~a" x))
     37 
     38      (define (newline)
     39        (format port "\n"))
     40 
     41      (define (timed-prime-test n)
     42        ;;  (newline)
     43        ;;  (display n)
     44        (start-timed-test n (runtime)))
     45 
     46      (define (start-timed-test n start-time)
     47        (cond
     48         ((prime? n)
     49          (newline)
     50          (display "[")
     51          (display n)
     52          (report-prime (- (runtime)
     53                           start-time)))
     54         (else  #f)))
     55 
     56      (define (report-prime elapsed-time)
     57        (display ", ")
     58        (display elapsed-time)
     59        (display "],")
     60        (newline)
     61        #t)
     62 
     63      (define (search-for-primes start-number end-number)
     64        (cond
     65         ((> start-number end-number) '())
     66         ((timed-prime-test start-number)
     67          (cons start-number
     68                (search-for-primes (+ start-number 2) end-number)))
     69         (else (search-for-primes (+ start-number 2) end-number))))
     70 
     71      (display "[")
     72 
     73      (search-for-primes 3 100001)
     74 
     75      (display "]")
     76      (newline))))