diff --git a/CHANGELOG.md b/CHANGELOG.md index 9229950..3a64b54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 \ No newline at end of file diff --git a/README.md b/README.md index 3c36783..3153d7e 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/lib.rs b/src/lib.rs index 3d961d2..576f1f1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,3 +2,4 @@ #![no_std] pub mod gamma; +pub mod n_choose_k; diff --git a/src/n_choose_k.rs b/src/n_choose_k.rs new file mode 100644 index 0000000..3b8ee37 --- /dev/null +++ b/src/n_choose_k.rs @@ -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(self, k: I) -> Option; +} + +impl BinomialCoefficient for N { + fn choose(self, k: I) -> Option { + 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)); + } +}