Add support for calculating binomial coefficients
All checks were successful
Hydra x86_64-linux.packages.extra-math Hydra build #3372 of procyos:extra_math:x86_64-linux.packages.extra-math
Hydra x86_64-linux.checks.extra-math Hydra build #3373 of procyos:extra_math:x86_64-linux.checks.extra-math

This commit is contained in:
Charlotte 🦝 Delenk 2024-09-09 11:57:27 +02:00
parent 22b3db918b
commit 90d36ddc34
4 changed files with 45 additions and 3 deletions

View file

@ -7,7 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
### Added
- Code for N-choose-k
## [0.1.0] - 2024-09-06
### Added ### Added
- Added implementations for incomplete gamma functions, converted from Math.Net - 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

View file

@ -30,8 +30,7 @@ repository](https://github.com/PurpleBooth/a-good-readme-template/tags).
## Authors ## Authors
- **Billie Thompson** - *Provided README Template* - - **Charlotte 🦝 Delenk** [DarkKirb](https://lotte.chir.rs)
[PurpleBooth](https://github.com/PurpleBooth)
See also the list of See also the list of
[contributors](https://github.com/PurpleBooth/a-good-readme-template/contributors) [contributors](https://github.com/PurpleBooth/a-good-readme-template/contributors)

View file

@ -2,3 +2,4 @@
#![no_std] #![no_std]
pub mod gamma; pub mod gamma;
pub mod n_choose_k;

36
src/n_choose_k.rs Normal file
View 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));
}
}