SICP练习1.16,我的bug在哪里,因为它看起来对我来说是正确的
我刚刚开始阅读这本书是为了好玩;我希望这是家庭作业,但我永远无法负担麻省理工学院的学费,而且还有很多比我聪明的人。 :p
fast-exp 应该找到 b^n,即 4^2 = 16, 3^3 = 27
(define (fast-exp b n)
(define (fast-exp-iter n-prime a)
(cond ((= n-prime 1) a)
((= (remainder n-prime 2) 1) (fast-exp-iter (- n-prime 1) (* a b)))
(else (fast-exp-iter (/ n-prime 2) (* a b b)))))
(fast-exp-iter n 1))
fast-exp 4 2; Expected 16, Actual 2
I've just started working through this book for fun; I wish it were homework, but I could never afford to attend MIT, and there are tons of people smarter than me anyway. :p
fast-exp is supposed to find b^n, i.e. 4^2 = 16, 3^3 = 27
(define (fast-exp b n)
(define (fast-exp-iter n-prime a)
(cond ((= n-prime 1) a)
((= (remainder n-prime 2) 1) (fast-exp-iter (- n-prime 1) (* a b)))
(else (fast-exp-iter (/ n-prime 2) (* a b b)))))
(fast-exp-iter n 1))
fast-exp 4 2; Expected 16, Actual 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您忘记调用 fast-exp。相反,您评估了三个单独的原子。要实际评估 4 到 2 的快速表达式,您必须编写
You forgot to call fast-exp. Instead, you evaluated three separate atoms. To actually evaluate the fast-exp of 4 to the 2, you'd have to write
您在这里写的解决方案也是不正确的。例如签出(fast-exp 2 6)。预期:64,实际:32。
The solution you have written here is also incorrect. e.g. Check out (fast-exp 2 6). Expected: 64, actual: 32.
你的解决方案是计算错误的答案。 (请参阅http://ideone.com/quT6A)事实上,原则上如何编写尾递归快速取幂仅传递两个数字作为参数?我认为这是不可能的,因为在计算过程中,如果遇到奇数指数,您不知道要使用什么乘数。
但我可以给出一个工作解决方案的例子,这正是 SICP 作者所期望的(使用“不变量”(a * b^n)的迭代过程,其中 a 最初为 1)
Your solution is calculating wrong answers. (See http://ideone.com/quT6A) In fact, how you in principle can write a tail-recursive fast exponentiation passing only two numbers as arguments? I don't think it's even possible, because in the middle of computation you don't know what multiplier to use if you encounter odd exponent.
But I can give an example of working solution that is exactly what is expected by SICP authors (iterative process using "invariant quantity" (a * b^n), where a is initially 1)