Open Source WEB

##(link2sicp "book-Z-H-11.html#%_thm_1.22" "Exercise 1.22")

解答例

Gauche には runtime という手続きではないので、srfi-19 モジュールの手続き current-time を利用する。

(use srfi-19)

すこしだけ、変更を加える

(define (timed-prime-test n)
  (newline)
  (display n)
  (start-prime-test n (current-time)))

(define (start-prime-test n start-time)
  (and (prime? n)
       (report-prime (time-difference (current-time) start-time))))

(define (report-prime elapsed-time)
  (display " *** ")
  (display elapsed-time)
  #t)

search-for-primes の定義は以下のとおり

(define (search-for-primes from n)
  (cond ((= n 0) (newline) 'done)
        ((even? from) (search-for-primes (+ from 1) n))
        ((timed-prime-test from) (search-for-primes (+ from 2) (- n 1)))
        (else (search-for-primes (+ from 2) n))))

実行例

gosh> (search-for-primes 1000 3)

1001
1003
1005
1007
1009 *** #<time-duration 0.000080000>
1011
1013 *** #<time-duration 0.000079000>
1015
1017
1019 *** #<time-duration 0.000095000>
done
gosh> (search-for-primes 10000 3)

10001
10003
10005
10007 *** #<time-duration 0.000250000>
10009 *** #<time-duration 0.000273000>
10011
10013
10015
10017
10019
10021
10023
10025
10027
10029
10031
10033
10035
10037 *** #<time-duration 0.000276000>
done
gosh> (search-for-primes 100000 3)

100001
100003 *** #<time-duration 0.000843000>
100005
100007
100009
100011
100013
100015
100017
100019 *** #<time-duration 0.000817000>
100021
100023
100025
100027
100029
100031
100033
100035
100037
100039
100041
100043 *** #<time-duration 0.000806000>
done
gosh> (search-for-primes 1000000 3)

1000001
1000003 *** #<time-duration 0.002689000>
1000005
1000007
1000009
1000011
1000013
1000015
1000017
1000019
1000021
1000023
1000025
1000027
1000029
1000031
1000033 *** #<time-duration 0.002586000>
1000035
1000037 *** #<time-duration 0.002628000>
done

計測時間のデータを見るかぎり、n の大きさが10倍になると、計算に必要な時間は ほぼ√10倍になっている。計測データは、プログラムが計算に必要なステップ数に 比例した時間で走るという考え方を支持すると考えてよい。

コード

##(sicp-answer-code "ex-1.22.scm")

このサイトは、 IPA の「平成15年度オープンソフトウエア活用基盤整備事業」 の委託事業として開発されたKahuaで試験的に運用しております。

Copyright (c) 2004-2007 株式会社タイムインターメディア About Us