(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 (+ test-divisor 1))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) (define (find-prime n k) (cond ((even? n) (find-prime (+ n 1) k)) ((= k 0) #t) ((prime? n) (find-prime (+ n 2) (- k 1))) ((not (prime? n)) (find-prime (+ n 2) k)))) (define (start-prime-test n start-time k) (if (find-prime n k) (- (runtime) start-time))) (define (time-prime-test n k) (start-prime-test n (runtime) k))
(time-prime-test 100000000000 3)
;Value: 5.178
(time-prime-test 1000000000000 3)
;Value: 14.943000000000001
(time-prime-test 10000000000000 3)
;Value: 70.16499999999999
(time-prime-test 10000000000 3)
;Value: 1.9200000000000017
总体来说还是比较贴近
为了能在PLT下面运行
语言包改成了Swindle,调用了primitive called current-milliseconds
(define (runtime) (current-milliseconds)) (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 (+ test-divisor 1))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) (define (find-prime n k) (cond ((even? n) (find-prime (+ n 1) k)) ((= k 0) #t) ((prime? n) (find-prime (+ n 2) (- k 1))) ((not (prime? n)) (find-prime (+ n 2) k)))) (define (start-prime-test n start-time k) (if (find-prime n k) (- (runtime) start-time))) (define (time-prime-test n k) (start-prime-test n (runtime) k))
> (time-prime-test 1000 3)
1
> (time-prime-test 10000 3)
1
> (time-prime-test 100000 3)
3
> (time-prime-test 10000000000 3)
1411
> (time-prime-test 100000000000 3)
3727
> (time-prime-test 1000000000000 3)
11193