peroxide/statistics/ops.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
/// Factorial
///
/// # Type
/// : `usize -> usize`
///
/// # Usage
///
/// ```
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// assert_eq!(factorial(5), 120);
/// ```
pub fn factorial(n: usize) -> usize {
let mut p = 1usize;
for i in 1..(n + 1) {
p *= i;
}
p
}
/// Double Factorial
///
/// # Type
/// : `usize -> usize`
///
/// # Usage
///
/// ```
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// assert_eq!(double_factorial(7), 105);
/// ```
pub fn double_factorial(n: usize) -> usize {
let mut s = 1usize;
let mut n = n;
while n >= 2 {
s *= n;
n -= 2;
}
s
}
/// Permutation
///
/// # Usage
///
/// ```
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// assert_eq!(P(5,3), 60);
/// ```
#[allow(non_snake_case)]
pub fn P(n: usize, r: usize) -> usize {
let mut p = 1usize;
for i in 0..r {
p *= n - i;
}
p
}
/// Combination
///
/// # Usage
///
/// ```
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// assert_eq!(C(10, 9), 10);
/// ```
#[allow(non_snake_case)]
pub fn C(n: usize, r: usize) -> usize {
if r > n / 2 {
return C(n, n - r);
}
P(n, r) / factorial(r)
}
/// Combination with Repetition
///
/// # Usage
///
/// ```
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// assert_eq!(H(5,3), C(7,3));
/// ```
#[allow(non_snake_case)]
pub fn H(n: usize, r: usize) -> usize {
C(n + r - 1, r)
}