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


 
// Little Man Computer
// Reads an integer n and prints n factorial
// Works for n = 0..6
        LDA one    // initialize factorial to 1
        STA fac
        INP        // get n from user
        BRZ done   // if n = 0, return 1
        STA n      // else store n
        LDA one    // initialize k = 1
outer   STA k      // outer loop: store latest k
        LDA n      // test for k = n
        SUB k
        BRZ done   // done if so
        LDA fac    // save previous factorial
        STA prev
        LDA k      // initialize i = k
inner   STA i      // inner loop: store latest i
        LDA fac    // build factorial by repeated addition
        ADD prev
        STA fac
        LDA i      // decrement i
        SUB one
        BRZ next_k // if i = 0, move on to next k
        BRA inner  // else loop for another addition
next_k  LDA k      // increment k
        ADD one   
        BRA outer  // back to start of outer loop  
done    LDA fac    // done, load the result
        OUT        // print it
        HLT        // halt
n       DAT 0      // input value
k       DAT 0      // outer loop counter, 1 up to n
i       DAT 0      // inner loop counter, k down to 0
fac     DAT 0      // holds k!, i.e. n! when done
prev    DAT 0      // previous value of fac
one     DAT 1      // constant 1
// end
 