Factorial Algorithm in Lisp/Scheme


Below you’ll find a recursive and an iterative version of the Factorial algorithm in Lisp/Scheme, based on the book Structure and Interpretation of Computer Programs (SICP).

Recursive

(define (factorial n)
        (if (= n 1)
                1
                (* n (factorial (- n 1) ))
        ))

(display (factorial 7))

Iterative


(define (factorial n)
        (define (iter product counter)
                (if (> counter n)
                        product
                        (iter (* counter product) (+ counter 1))
                ))
        (iter 1 1))

(display (factorial 7))

Notice that in this version the procedure (i.e., the function) is still recursive, as it’s defined in terms of itself. However, since it’s a tail recursion, the Lisp interpreter/compiler will generate an iterative process, where the variables will be kept through out all iterations.

One thought on “Factorial Algorithm in Lisp/Scheme

Leave a Reply

Your email address will not be published. Required fields are marked *