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


 
MODULE Factorial;
IMPORT
  Out;
 
VAR 
  i: INTEGER;
 
  PROCEDURE Iterative(n: LONGINT): LONGINT;
  VAR
    i, r: LONGINT;
  BEGIN
    ASSERT(n >= 0);
    r := 1;
    FOR i := n TO 2 BY -1 DO
      r := r * i
    END;
    RETURN r
  END Iterative;
 
  PROCEDURE Recursive(n: LONGINT): LONGINT;
  VAR
    r: LONGINT;
  BEGIN
    ASSERT(n >= 0);
    r := 1;
    IF n > 1 THEN 
      r := n * Recursive(n - 1)
    END;
    RETURN r
  END Recursive;
 
BEGIN
  FOR i := 0 TO 9 DO
    Out.String("Iterative ");Out.Int(i,0);Out.String('! =');Out.Int(Iterative(i),0);Out.Ln;
  END;
  Out.Ln;
  FOR i := 0 TO 9 DO
    Out.String("Recursive ");Out.Int(i,0);Out.String('! =');Out.Int(Recursive(i),0);Out.Ln;
  END
END Factorial.
 