在 LISP 中使用尾递归的二项式系数
我想编写一个函数来使用尾递归查找 C(n,k),我将非常感谢您的帮助。
我已经达到了这个目的:
(defun tail-recursive-binomial (n k)
(cond ((or (< n k) (< k 0)) NIL)
((or (= k 0) (= n k)) 1)
(T (* (tail-recursive-binomial (- n 1) (- k 1)) (/ n k)))))
使用 二项式系数的以下性质。
但我不知道如何使递归调用成为每个实例执行的最后一条指令,因为最后一条是产品。我一直在尝试使用辅助功能,我认为这是唯一的方法,但我还没有找到解决方案。
I want to program a function to find C(n,k) using tail recursion, and I would greatly appreciate your help.
I have reached this:
(defun tail-recursive-binomial (n k)
(cond ((or (< n k) (< k 0)) NIL)
((or (= k 0) (= n k)) 1)
(T (* (tail-recursive-binomial (- n 1) (- k 1)) (/ n k)))))
Using the following property of the binomial coefficients.
But I don't know how to make the recursive call to be the last instruction executed by each instance, since there the last one is the product. I have been trying it by using an auxiliary function, which I think is the only way, but I haven't found a solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 starblue 建议的那样,使用递归辅助函数:
或者,为主函数提供一个 可选 累加器参数默认值为 1(递归基本情况):
后一个选项的效率稍低,因为在每次递归调用中都会检查错误条件。
As starblue suggests, use a recursive auxiliary function:
Or, give the main function an optional accumulator argument with a default value of 1 (the recursive base case):
The latter option is slightly less efficient, since the error condition is checked in every recursive call.
您需要一个带有额外参数的辅助函数,用于计算和传递结果。
You need an auxiliary function with an extra argument, which you use for computing and passing the result.