理系学生日記

おまえはいつまで学生気分なのか

忍者TOOLS

問題1-23

smallest-divisorをちょっとだけ早くしようとかいう問題ですが、1-1でもいいくらい簡単くさくて、nextを定義すればよいだけぽい。

(use srfi-19)
(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 (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-time)))

(define (start-prime-test n called-time)
  (if (prime? n)
      (report-prime (time-difference (current-time) called-time))
      #f))

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

(define (next n)
  (if (= n 2) 3
      (+ n 2)))

ただ、もちろん精度の関係で時間は計れない。いや、これも大きい素数を調べりゃいいんだけど。

gosh> (timed-prime-test 1000037)
1000037 *** #<time-duration 0.000000000>#t