xsf/scipy_special/perm.rs
1use num_traits::{ConstOne, NumOps};
2
3/// $k$-permutations of $n$ things, $_nP_k$
4///
5/// Permutations of $n$ things taken $k$ at a time, also known as "partial permutations".
6/// It can be written in terms of the falling factorial, but unlike
7/// [`xsf::pow_falling`](crate::pow_falling), this function computes the result exactly for integer
8/// types.
9///
10/// Corresponds to [`scipy.special.perm(n, k, exact=True)`][perm].
11///
12/// [perm]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.perm.html
13///
14/// # Types
15/// - `N`: Any numeric type supporting basic arithmetic operations
16///
17/// # Returns
18/// The number of $k$-permutations of $n$, i.e. $n(n-1)(n-2) \cdots (n-k+1)$
19///
20/// # See also
21/// - [`comb`](crate::comb): $k$-combinations of $n$ things, $_nC_k$
22/// - [`factorial`](crate::factorial): factorial $n!$, the special case $k = n$
23/// - [`pow_falling`](crate::pow_falling): falling factorial power function
24#[inline]
25pub fn perm<N: NumOps + ConstOne + Copy>(n: N, k: u32) -> N {
26 (0..k).fold((N::ONE, n), |(p, j), _| (p * j, j - N::ONE)).0
27}