開発環境
計算機プログラムの構造と解釈[第2版](ハロルド エイブルソン (著)、ジュリー サスマン (著)、ジェラルド・ジェイ サスマン (著)、Harold Abelson (原著)、Julie Sussman (原著)、Gerald Jay Sussman (原著)、和田 英一 (翻訳)、翔泳社、原著: Structure and Interpretation of Computer Programs (MIT Electrical Engineering and Computer Science)(SICP))の第1章(手続きによる抽象の構築)、1.2(手続きとその生成するプロセス)、1.2.6(例: 素数性のテスト)、問題1.23.を取り組んでみる。
その他参考書籍
問題1.23.
コード(Emacs)
(begin (newline) (load "procedures.scm") (define nums '(1000 100000)) (define count 0) (define (smallest-divisor n) (find-divisor n 2)) (define (next n) (if (= n 2) 3 (+ n 2))) (define (find-divisor n test-divisor) (if (> (square test-divisor) n) n (if (divides? test-divisor n) test-divisor (find-divisor n (next test-divisor))))) (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 (current-second))) (define (start-prime-test n start-time) (if (prime? n) ((lambda () (set! count (+ count 1)) (report-prime (- (current-second) start-time)))))) (define (report-prime elapsed-time) (display " *** ") (display elapsed-time)) (define (iter n) (if (not (= count 3)) ((lambda () (timed-prime-test n) (iter (+ n 1)))))) ;; 毎回入力が 2 か調べたり、合成手続き呼び出しになったりするから、二倍よりは遅くなる (for-each (lambda (n) (set! count 0) (iter n)) nums) (newline) 'done)
入出力結果(Terminal(kscheme), REPL(Read, Eval, Print, Loop))
$ ksi < sample23.scm ksi> 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 *** 0.07959103584289551 1010 1011 1012 1013 *** 0.09845900535583496 1014 1015 1016 1017 1018 1019 *** 0.0858919620513916 100000 100001 100002 100003 *** 0.8235759735107422 100004 100005 100006 100007 100008 100009 100010 100011 100012 100013 100014 100015 100016 100017 100018 100019 *** 0.8860750198364258 100020 100021 100022 100023 100024 100025 100026 100027 100028 100029 100030 100031 100032 100033 100034 100035 100036 100037 100038 100039 100040 100041 100042 100043 *** 0.8975110054016113 => done ksi> $
0 コメント:
コメントを投稿