ITeye博客

2011 年文章归档

共 7 篇文章

sicp练习 1.22

(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…

2011-05-27 22:33 · Structure and Interpretation of Computer Programs

sicp练习1.21用smallest-divisor寻找最小因子

(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)) (smallest-divi…

2011-05-22 14:36 · Structure and Interpretation of Computer Programs

sicp练习1.20 gcd过程 应用序 正则序 remainder次数

(define (gcd a b remainder-count) (if(= b 0) (begin (display "\nremainder count: ") (display remainder-count) (display "\n gcd result:") (display a) (display "\n") a) (gcd b (remainder a b) (+ remainder-count 1)))) (gcd 12 9 0) ;(gcd 12 28 0) (define (new-if predicate then-clause else-clause) (cond…

2011-05-17 09:41 · Structure and Interpretation of Computer Programs

sicp练习1.18 基于加法、加倍和折半运算求两个整数之乘积

;double的功能是2*n (define (double n) (+ n n)) (double 5) ;havle-iter函数的功能是通过迭代获得n的一半的值,guess是初始猜测值 (define (havle-iter guess n) (cond ((not (integer? n)) (display "error: 原因havle函数的参数是整数\n")) (( and (< (double guess) n) (<= (double (+ guess 1)) n)) (havle-iter (+ 1 guess) n)) (( and (> (double guess) …

2011-05-13 23:32 · Structure and Interpretation of Computer Programs

sicp练习1.17 只有加减法 实现快速求幂

;double的功能是2*n (define (double n) (+ n n)) (double 5) ;*函数的功能是a乘以b (define (* a b) (if (= b 0) 0 (+ a (* a (- b 1))))) (* 3 4) ;havle-iter函数的功能是通过迭代获得n的一半的值,guess是初始猜测值 (define (havle-iter guess n) (cond ((not (integer? n)) (display "error: 原因havle函数的参数是整数\n")) (( and (< (double guess) n) (<= (doub…

2011-05-13 20:37 · Structure and Interpretation of Computer Programs

快速求幂 sicp练习1.16

(define (even? n) (= (remainder n 2) 0)) (define (fast-expt-iter result b n) (cond ((= n 0) 1) ((= n 1) (* result b)) ((even? n) (fast-expt-iter result (* b b) (/ n 2))) (else(fast-expt-iter (* b result) b (- n 1))))) (define (fast-expt b n) (fast-expt-iter 1 b n) ) (fast-expt 2 0) (fast-expt 2 1) …

2011-05-13 13:02 · Structure and Interpretation of Computer Programs

sicp练习1.12 帕斯卡三角(杨辉三角)

杨辉三角以前在学习c语言时候,用循环很容易实现。由于刚刚接触函数式语言,递归和迭代方式实现循环还没深入我心。下意思的想用链表来实现,但发现自己对scheme的链表操作太不熟悉,总会出现这样那样子的无法自我解释的问题。最后参考了@dennis_zane的pascal实现,dennis_zane是把杨辉三角左对齐,然后根据坐标之间的关系实现:(pascal x y) ,其中x,y为坐标,(pascal x y) 的值为坐标对应的杨辉三角数值。看了dennis_zane的实现以后,很惭愧自己没有想到。想想其未最终打印出结果,那我来继续完成其工作。当然也是用递归和迭代。 (define (pasca…

2011-05-13 08:21 · Structure and Interpretation of Computer Programs