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


// ----------------
// recursive method  (requires INTV_T input parm)
// ----------------
 
fact_r @FN [n] 
{  
    @CASE
      when:(n <  0iv) {-1iv                 }
      when:(n == 0iv) { 1iv                 } 
      else:           { n * (@fact_r n-1iv) } 
};
 
 
// ----------------
// iterative method  (requires INTV_T input parm) 
// ----------------
 
fact_i @FN [n]
{
    @CASE 
      when:(n <  0iv) {-1iv } 
      when:(n == 0iv) { 1iv }
      else:           {
                        @VAR i fact = 1iv 1iv;
                        @LOOP while:(i <= n) { fact *= i++ };
                      }
};
 
 
// ------------------
// Display factorials
// ------------------
 
@VAR i = -1iv; 
@LOOP times:15
{
     @SAY «recursive  » i «! = » (@fact_r i) between:"";   
     @SAY «iterative  » i «! = » (@fact_i i) between:"";  
 
     i = 5iv * i / 4iv + 1iv;
}; 
 
 
/]========================================================================================= 
 
Output:
 
recursive  -1! = -1
iterative  -1! = -1
recursive  0! = 1
iterative  0! = 1
recursive  1! = 1
iterative  1! = 1
recursive  2! = 2
iterative  2! = 2
recursive  3! = 6
iterative  3! = 6
recursive  4! = 24
iterative  4! = 24
recursive  6! = 720
iterative  6! = 720
recursive  8! = 40320
iterative  8! = 40320
recursive  11! = 39916800
iterative  11! = 39916800
recursive  14! = 87178291200
iterative  14! = 87178291200
recursive  18! = 6402373705728000
iterative  18! = 6402373705728000
recursive  23! = 25852016738884976640000
iterative  23! = 25852016738884976640000
recursive  29! = 8841761993739701954543616000000
iterative  29! = 8841761993739701954543616000000
recursive  37! = 13763753091226345046315979581580902400000000
iterative  37! = 13763753091226345046315979581580902400000000
recursive  47! = 258623241511168180642964355153611979969197632389120000000000
iterative  47! = 258623241511168180642964355153611979969197632389120000000000