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


/* NetRexx */
 
options replace format comments java crossref savelog symbols nobinary
 
numeric digits 64 -- switch to exponential format when numbers become larger than 64 digits
 
say 'Input a number: \-'
say
do
  n_ = long ask -- Gets the number, must be an integer
 
  say n_'! =' factorial(n_) '(using iteration)'
  say n_'! =' factorial(n_, 'r') '(using recursion)'
 
  catch ex = Exception
    ex.printStackTrace
end
 
return
 
method factorial(n_ = long, fmethod = 'I') public static returns Rexx signals IllegalArgumentException
 
  if n_ < 0 then -
    signal IllegalArgumentException('Sorry, but' n_ 'is not a positive integer')
 
  select
    when fmethod.upper = 'R' then -
      fact = factorialRecursive(n_)
    otherwise -
      fact = factorialIterative(n_)
    end
 
  return fact
 
method factorialIterative(n_ = long) private static returns Rexx
 
  fact = 1
  loop i_ = 1 to n_
    fact = fact * i_
    end i_
 
  return fact
 
method factorialRecursive(n_ = long) private static returns Rexx
 
  if n_ > 1 then -
    fact = n_ * factorialRecursive(n_ - 1)
  else -
   fact = 1
 
  return fact