sicp习题试解 (1.27)

类别:编程语言 点击:0 评论:0 推荐:

; ======================================================================
;
; Structure and Interpretation of Computer Programs
; (trial answer to excercises)
;
; 计算机程序的构造和解释(习题试解)
;
; created: code17 02/28/05
; modified:
; (保持内容完整不变前提下,可以任意转载)
; ======================================================================

;; SICP No.1.27

;; 原始的try-it函数定义为测试某数a对于n的expmod,现在改为递归测试从a至1
;; 的所有整数,函数fermat-test以n调用try-it
(define (fermat-test n)
(define (try-it a)
(cond ((= a 0) #t)
((= (expmod a n n) a) (try-it (- a 1)))
(else #f)))
(try-it (- n 1)))


;; Test-it:
;; Welcome to MzScheme version 209, Copyright (c) 2004 PLT Scheme, Inc.
;; > (fermat-test 561)
;; #t
;; > (fermat-test 1105)
;; #t
;; > (fermat-test 1729)
;; #t
;; > (fermat-test 2465)
;; #t
;; > (fermat-test 2821)
;; #t
;; > (fermat-test 6601)
;; #t
;; >

本文地址:http://com.8s8s.com/it/it23143.htm