Skip to content

Instantly share code, notes, and snippets.

@yanfeng42
Last active February 13, 2021 00:58
Show Gist options
  • Save yanfeng42/8acfd4cec640f7ca976c053917f28656 to your computer and use it in GitHub Desktop.
Save yanfeng42/8acfd4cec640f7ca976c053917f28656 to your computer and use it in GitHub Desktop.
sicp 1.22 的chez scheme 实现.
;; 基于 https://cisco.github.io/ChezScheme/csug9.5/csug9_5.pdf 的 12.10. Times and Dates
(define (time-prime-test n)
(newline)
(display n)
(start-prime-test n (current-time))
)
(define (start-prime-test n start-time)
(if (prime? n)
(report-prime (time-difference (current-time) start-time))
)
)
(define (report-prime elapsed-time)
(display " *** ")
; 输出的是纳秒.
(display (time-nanosecond elapsed-time))
)
(define (search-for-primes n)
(search-for-primes-counter n 3)
)
(define (search-for-primes-counter n count)
(if (> count 0)
(if (even? n)
(search-for-primes-counter (+ n 1) count)
; 知识点: 平级子句, 用 begin 连接.
(if (prime? n)
(begin
(time-prime-test n)
(search-for-primes-counter (+ n 2) (- count 1))
)
(search-for-primes-counter (+ n 2) count)
)
)
)
)
@yanfeng42
Copy link
Author

; > (search-for-primes 1000)

; 1009 *** 1600
; 1013 *** 1300
; 1019 *** 1200
; > (search-for-primes 10000)

; 10007 *** 2500
; 10009 *** 2400
; 10037 *** 12500
; > (search-for-primes 100000)

; 100003 *** 9100
; 100019 *** 5800
; 100043 *** 5800
; > (search-for-primes 1000000)

; 1000003 *** 25500
; 1000033 *** 17400
; 1000037 *** 33300

; 因为现在速度很快, 所以需要较大的值, 才能观察出差异.

; > (search-for-primes 10000000000)   (1e9)

; 10000000019 *** 2062000
; 10000000033 *** 1711700
; 10000000061 *** 1809700
; > (search-for-primes 100000000000)  (1e10)

; 100000000003 *** 5356800
; 100000000019 *** 5268800
; 100000000057 *** 5430700
; > (search-for-primes 1000000000000) (1e11)

; 1000000000039 *** 17144200
; 1000000000061 *** 17688500
; 1000000000063 *** 17132100

@yanfeng42
Copy link
Author

相较 http://community.schemewiki.org/?sicp-ex-1.22 而言, 我的实现, 可以直接求得最终的结果,且不用修改 time-prime-test 的定义.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment