SketchyLISP Reference |
Copyright (C) 2007 Nils M Holm |
<<[expt] | [Index] | [filter]>> |
Conformance: SketchyLISP Extension
Purpose:
Compute the factorial of a number.
This procedure uses the "recursive product" algorithm.
The argument must be a positive integer.
The algorithm (in Java) was found under
"factorial functions" at
http://www.luschny.de/math/
Arguments:
N - number
Model:
(define (factorial n) (cond ((zero? n) 1) (#t (* n (factorial (- n 1))))))
Implementation:
(define (factorial n) (letrec ((r* (lambda (n k) (cond ((< k 2) n) (else (let ((l (quotient k 2))) (* (r* n l) (r* (+ n l) (- k l))))))))) (cond ((negative? n) (bottom (list 'factorial n))) (else (r* 1 n)))))
Example:
(factorial 5) => 120
<<[expt] | [Index] | [filter]>> |