View Raw SPL
/*****************************************************************************
*                                                                            *
*   FACTORIAL.SPL  Copyright (C) 2014 DSP Development Corporation            *
*                               All Rights Reserved                          *
*                                                                            *
*   Author:    Randy Race                                                    *
*                                                                            *
*   Synopsis:  Computes the factorial of a positive integer or series        *
*                                                                            *
*   Revisions: 15 May 2014  RRR  Creation                                    *
*                                                                            *
*****************************************************************************/


#if @HELP_FACTORIAL

    FACTORIAL

    Purpose: Computes the factorial for positive integers.

    Syntax:  FACTORIAL(n)

                     n - A scalar or series. Must contain integer
                         values >= 0.

    Returns: A scalar or series.

    Example:
             factorial(6)

             returns 720

    Example:
             W1: 0..10
             W2: factorial(W1)

             W2 == {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}

    Remarks:
             For integer N, FACTORIAL returns the product of all integer
             values 1..N, thus:

             factorial(n) == prod(1..n)

             For a series, FACTORIAL returns the factorial for each element.

             Using double precision accuracy, FACTORIAL is precise up to
             n == 21 and will retain 15 digits of accuracy for n > 21.

             See GAMMA for a generalized factorial function that operates
             on real or complex input values.

    See Also:
             Bincoeff
             Gamma
             Nchoosek
             Prod
#endif


/* remove old GAMMA macro */
#undef GAMMA

/* integer factorial */
factorial(n)
{
        if (any(not(n == int(n))) || any(n < 0) || iscomplex(n))
        {
                error("factorial - input must contain only non-negative integers");
        }

        /* gamma is exact for integer n up to 15 digits */
        return(gamma(n + 1));
}