Definitions

   The factorial of   0   (zero)   is defined as being   1   (unity).
   The   Factorial Function   of a positive integer,    n,    is defined as the product of the sequence:
                 n,   n-1,   n-2,   ...   1 



Task

Write a function to return the factorial of a number.

Solutions can be iterative or recursive.

Support for trapping negative    n    errors is optional.



Related task

   Primorial numbers


 
REDIM fac#(0)
Factorial fac#(), 655, 10, power#
PRINT power#
SUB Factorial (fac#(), n&, numdigits%, power#)
power# = 0
fac#(0) = 1
remain# = 0
stx& = 0
slog# = 0
NumDiv# = 10 ^ numdigits%
FOR fac# = 1 TO n&
    slog# = slog# + LOG(fac#) / LOG(10)
    FOR x& = 0 TO stx&
        fac#(x&) = fac#(x&) * fac# + remain#
        tx# = fac#(x&) MOD NumDiv#
        remain# = (fac#(x&) - tx#) / NumDiv#
        fac#(x&) = tx#
    NEXT
    IF remain# > 0 THEN
        stx& = UBOUND(fac#) + 1
        REDIM _PRESERVE fac#(stx&)
        fac#(stx&) = remain#
        remain# = 0
    END IF
NEXT
 
scanz& = LBOUND(fac#)
DO
    IF scanz& < UBOUND(fac#) THEN
        IF fac#(scanz&) THEN
            EXIT DO
        ELSE
            scanz& = scanz& + 1
        END IF
    ELSE
        EXIT DO
    END IF
LOOP
 
FOR x& = UBOUND(fac#) TO scanz& STEP -1
    m$ = LTRIM$(RTRIM$(STR$(fac#(x&))))
    IF x& < UBOUND(fac#) THEN
        WHILE LEN(m$) < numdigits%
            m$ = "0" + m$
        WEND
    END IF
    PRINT m$; " ";
    power# = power# + LEN(m$)
NEXT
power# = power# + (scanz& * numdigits%) - 1
PRINT slog#
END SUB
 