Eric
Eric

Reputation: 399

lisp do loop factorial code

(defun fact (n)
    (do
       ((i 1 (+ 1 i))
        (prod 1 (* i prod)))
       ((equal i n) prod)))

I have done the code above and when i try, fact(4), it give me ans is 6. I am not sure what is going wrong. Can anyone help me?

Upvotes: -1

Views: 4764

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139261

Mihai has already given the answer.

I would write it as:

(defun fact (n)
  (do ((i    1 (+ 1 i))
       (prod 1 (* i prod)))
      ((> i n) prod)))

Common Lisp has all the usual arithmetic predicates which work for numbers: =, <, >, ...

Upvotes: 3

Mihai Maruseac
Mihai Maruseac

Reputation: 21445

Change to

(defun fact (n)
    (do
       ((i 1 (+ 1 i))
        (prod 1 (* i prod)))
       ((equal i (+ n 1)) prod)))

Basically, you were doing one iteration less than necessary.

Upvotes: 3

Related Questions