Reputation: 399
(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
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
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