开发者

Binomial Coefficient using Tail Recursion in LISP

开发者 https://www.devze.com 2023-01-22 14:06 出处:网络
I want to program a function to find C(n,k) using tail recursion, and I would greatly appreciate your help.

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 (* (tai开发者_StackOverflowl-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.


As starblue suggests, use a recursive auxiliary function:

(defun binom (n k)
  (if (or (< n k) (< k 0))
    NIL  ; there are better ways to handle errors in Lisp
    (binom-r n k 1)))

;; acc is an accumulator variable
(defun binom-r (n k acc)
  (if (or (= k 0) (= n k))
    acc
    (binom-r (- n 1) (- k 1) (* acc (/ n k)))))

Or, give the main function an optional accumulator argument with a default value of 1 (the recursive base case):

(defun binom (n k &optional (acc 1))
  (cond ((or (< n k) (< k 0)) NIL)
        ((or (= k 0) (= n k)) acc)
        (T (binom (- n 1) (- k 1) (* acc (/ n k))))))

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号