Factorial of a number - LISP

Program:
;;FACTORIAL OF A NUMBER USING RECURSION AND ITERATION
(defun factorial(n)
    (format t "~&<<<Finding factorial of ~D>>>~&1.Iterative method~&2.Recursive method~&Enter your choice:" n)
    (setf x (read))
    (if (= x 1) (format t "factorial = ~D (using iteration)" (fact1 n)))
    (if (= x 2) (format t "factorial = ~D (using recursion)" (fact2 n)))
)
(defun fact1(n) ;;function for iterative method
    (setf f 1)
    (do ((i n (- i 1))) ((= i 1))
        (setf f (* f i))
    )
f)
(defun fact2(n) ;;function for recursive method
    (if (= n 0) 1
        (* n (fact2(- n 1)))
    )
)

Output:
Break 1 [2]> (load 'fact.lsp)
;; Loading file fact.lsp ...
;; Loaded file fact.lsp
T
Break 1 [2]> (factorial 5)
<<<Finding factorial of 5>>>
1.Iterative method
2.Recursive method
Enter your choice:1
factorial = 120 (using iteration)
NIL
Break 1 [2]> (factorial 5)
<<<Finding factorial of 5>>>
1.Iterative method
2.Recursive method
Enter your choice:2
factorial = 120 (using recursion)
NIL                   
Break 1 [2]>

1 comment:

Related Posts Plugin for WordPress, Blogger...