1 ## Copyright (C) 2000-2012 Paul Kienzle
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} factorial (@var{n})
21 ## Return the factorial of @var{n} where @var{n} is a positive integer. If
22 ## @var{n} is a scalar, this is equivalent to @code{prod (1:@var{n})}. For
23 ## vector or matrix arguments, return the factorial of each element in the
24 ## array. For non-integers see the generalized factorial function
26 ## @seealso{prod, gamma}
29 function x = factorial (n)
32 elseif (any (n(:) < 0 | n(:) != fix (n(:))))
33 error ("factorial: N must all be non-negative integers");
35 x = round (gamma (n+1));
38 %!assert (factorial(5), prod(1:5))
39 %!assert (factorial([1,2;3,4]), [1,2;6,24])
40 %!assert (factorial(70), exp(sum(log(1:70))), -128*eps)
41 %!fail ('factorial(5.5)', "must all be non-negative integers")
42 %!fail ('factorial(-3)', "must all be non-negative integers")