Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

combinations: count and size_hint #729

Merged
merged 14 commits into from
Aug 18, 2023
14 changes: 14 additions & 0 deletions src/combinations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,17 @@ impl<I> FusedIterator for Combinations<I>
where I: Iterator,
I::Item: Clone
{}

pub(crate) fn checked_binomial(mut n: usize, mut k: usize) -> Option<usize> {
if n < k {
return Some(0);
}
// `factorial(n) / factorial(n - k) / factorial(k)` but trying to avoid it overflows:
k = (n - k).min(k); // symmetry
let mut c = 1;
for i in 1..=k {
c = (c / i).checked_mul(n)?.checked_add((c % i).checked_mul(n)? / i)?;
n -= 1;
}
Some(c)
Philippe-Cholet marked this conversation as resolved.
Show resolved Hide resolved
}
Philippe-Cholet marked this conversation as resolved.
Show resolved Hide resolved