sicp习题 1.17 1.18解答
这两道题目没什么难度了,幂运算是连续乘,乘法运算就是连续加,改造一下书中的例子和习题1.16就可以了,还是分析一下。习题1.17:
已知两个过程,double过程可以求出一个整数的两倍,而halve过程将一个偶数除以2;要求写出一个过程,只用对数个步骤计算两个整数的乘积。
解答:
计算a*b,考虑两种情况:
1)当b是偶数时:
a*b=2(a*(b/2))
2)当b是奇数时:
a*b=a*(b-1)+a
通过递归直接得到lisp过程,很好理解了,预先定义了两个已知过程double和halve:
<div style="border: 1px solid #cccccc; padding: 4px 5px 4px 4px; background-color: #eeeeee; font-size: 13px; width: 98%;"><!---->(define (double x) (* x 2))
(define (halve x) (/ x 2))
(define (multiplied a b)
(cond ((or (= b 0) (= a 0)) 0)
((even? b) (double (multiplied a (halve b))))
(else (+ a (multiplied a (- b 1))))))
页:
[1]