%mathpiper,def="Subfactorial"

Function("Subfactorial",{n})
[
	n! * Sum(k,0,n,(-1)^(k)/k!);
];

30 # Subfactorial(n_IsList) <-- MapSingle("Subfactorial",n);

%/mathpiper



%mathpiper_docs,name="Subfactorial",categories="User Functions;Combinatorics"
*CMD Subfactorial  --- factorial and related functions
*CALL
	Subfactorial(m)

*PARMS
{m} -- integer

*DESC
The {Subfactorial} function can be interpreted as the  number of permutations of {m} objects in which no object 
appears in its natural place, also called "derangements." 

The factorial functions terminate and print an error message if the arguments are too large (currently the limit 
is $n < 65535$) because exact factorials of such large numbers are computationally expensive and most probably 
not useful. One can call {Internal'LnGammaNum()} to evaluate logarithms of such factorials to desired precision.

*E.G.
In> Subfactorial(10)
Result: 1334961;

*SEE BinomialCoefficient, Product, Gamma, ,! !!, ***,
%/mathpiper_docs

    %output,preserve="false"
      
.   %/output

