t3x.org / nss / factorial.html

(Nils' Scheme Snippets)

 
Paren matching: ON  |  Category: math  |  Overview  |  Scheme Books  |  License
 

(factorial integer) => integer

 
Purpose
Compute the factorial of a number.
 
Arguments
n factorial to compute
 
Example
(factorial 30) => 265252859812191058636308480000000
(define (factorial n)
  (letrec
    ((r* (lambda (n m)
           (cond ((< m 2) n)
                 (else (let ((k (quotient m 2)))
                         (* (r* n k)
                            (r* (+ n k) (- m k)))))))))
    (if (negative? n)
        (wrong "factorial: negative operand" n)
        (r* 1 n))))

Copyright (C) 2007 Nils M Holm <nmh @ t3x . org>