Generation of Fibonacci Series - Recursion & Iteration -LISP

Program:
;;FIBONACCI SERIES
(defun fib(n)
    (setf a 0 b 1)
    (format t "~&<<<Generation of Fibonacci series with ~D terms>>>~&1.Iterative method~&2.Recursive method~&Enter your choice:" n)
    (setf x (read))
    (cond
        ((= n 1) (print a))
        ((= n 2) (print a)(print b))
        ((> n 2) (if (= x 1)
                (fib1 n))
        (if (= x 2)
             (do ((i 0 (+ i 1))) ((= i n))
                (print (fib2 i)))))
    )
)
(defun fib1(n)
                ;Iterative method
    (print a)(print b)
    (do((i 2 (+ i 1))) ((= i n))
        (setf c (+ a b))
        (print c)
        (setf a b b c))
)
(defun fib2(n)
    (cond
        ((= n 0) 0)
        ((= n 1) 1)
        ((> n 1)(+ (fib2 (- n 1)) (fib2 (- n 2))))
                ;Recursive method
    )
)

Output:
Break 2 [3]> (load 'f.lsp)
;;  Loading file f.lsp ...
;;  Loaded file f.lsp
T
Break 2 [3]> (fib 5)
<<<Generation of Fibonacci series with 5 terms>>>
1.Iterative method
2.Recursive method
Enter your choice:1

0
1
1
2
3
NIL
Break 2 [3]> (fib 5)
<<<Generation of Fibonacci series with 5 terms>>>
1.Iterative method
2.Recursive method
Enter your choice:2

0
1
1
2
3
NIL
Break 2 [3]>

2 comments:

Related Posts Plugin for WordPress, Blogger...