Binomial coefficient using tail recursion in LISP

I want to program a function to find C (n, k) using tail recursion, and I would really appreciate your help.

I have achieved 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 binomial coefficients .

But I do not know how to make a recursive call the last command executed by each instance, since the latter is a product. I am trying to use it with a helper function, which, in my opinion, is the only way, but I have not found a solution.

+5
source share
2 answers

starblue, :

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

optional 1 ( ):

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

, .

+7

, .

+3

All Articles