generated from ProcyOS/rust-template
Add support for calculating binomial coefficients
This commit is contained in:
parent
22b3db918b
commit
90d36ddc34
4 changed files with 45 additions and 3 deletions
|
@ -7,7 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Code for N-choose-k
|
||||
|
||||
## [0.1.0] - 2024-09-06
|
||||
|
||||
### Added
|
||||
- Added implementations for incomplete gamma functions, converted from Math.Net
|
||||
|
||||
[Unreleased]: https://git.chir.rs/ProcyOS/rust-template
|
||||
[Unreleased]: https://git.chir.rs/ProcyOS/extra_math/compare/v0.1.0...main
|
||||
[0.1.0]: https://git.chir.rs/ProcyOS/extra_math/releases/tag/v0.1.0
|
|
@ -30,8 +30,7 @@ repository](https://github.com/PurpleBooth/a-good-readme-template/tags).
|
|||
|
||||
## Authors
|
||||
|
||||
- **Billie Thompson** - *Provided README Template* -
|
||||
[PurpleBooth](https://github.com/PurpleBooth)
|
||||
- **Charlotte 🦝 Delenk** [DarkKirb](https://lotte.chir.rs)
|
||||
|
||||
See also the list of
|
||||
[contributors](https://github.com/PurpleBooth/a-good-readme-template/contributors)
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
#![no_std]
|
||||
|
||||
pub mod gamma;
|
||||
pub mod n_choose_k;
|
||||
|
|
36
src/n_choose_k.rs
Normal file
36
src/n_choose_k.rs
Normal file
|
@ -0,0 +1,36 @@
|
|||
//! Calculates the binomial coefficient N-choose-K.
|
||||
|
||||
use num_traits::{Num, NumCast, PrimInt};
|
||||
|
||||
/// Calculates the binomial coefficient
|
||||
pub trait BinomialCoefficient: Num + NumCast {
|
||||
/// Calculates the binary coefficient N-choose-K.
|
||||
///
|
||||
/// # Return
|
||||
/// Returns None if k cannot be represented in the current number type.
|
||||
fn choose<I: PrimInt>(self, k: I) -> Option<Self>;
|
||||
}
|
||||
|
||||
impl<N: Num + NumCast + Copy> BinomialCoefficient for N {
|
||||
fn choose<I: PrimInt>(self, k: I) -> Option<Self> {
|
||||
let mut num = Self::one();
|
||||
let mut denom = Self::one();
|
||||
let mut i = I::one();
|
||||
while i <= k {
|
||||
num = num * (self + Self::one() - Self::from(i)?);
|
||||
denom = denom * Self::from(i)?;
|
||||
i = i + I::one();
|
||||
}
|
||||
Some(num / denom)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::n_choose_k::BinomialCoefficient;
|
||||
|
||||
#[test]
|
||||
fn test_binomial() {
|
||||
assert_eq!(BinomialCoefficient::choose(4, 2), Some(6));
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue