Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/adaptors/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -834,8 +834,9 @@ impl_tuple_combination!(Tuple10Combination Tuple9Combination; a b c d e f g h i)
impl_tuple_combination!(Tuple11Combination Tuple10Combination; a b c d e f g h i j);
impl_tuple_combination!(Tuple12Combination Tuple11Combination; a b c d e f g h i j k);

/// Computes the binomial coefficient, returning `None` if it overflows `usize`.
// https://en.wikipedia.org/wiki/Binomial_coefficient#In_programming_languages
pub(crate) fn checked_binomial(mut n: usize, mut k: usize) -> Option<usize> {
pub fn checked_binomial(mut n: usize, mut k: usize) -> Option<usize> {
if n < k {
return Some(0);
}
Expand Down
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,9 @@ pub mod traits {
pub use crate::tuple_impl::HomogeneousTuple;
}

// Shared with integration tests.
#[doc(hidden)]
pub use crate::adaptors::checked_binomial;
#[cfg(feature = "use_alloc")]
use crate::combinations_with_replacement::ArrayCombinationsWithReplacement;
pub use crate::concat_impl::concat;
Expand Down
6 changes: 1 addition & 5 deletions tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -962,11 +962,7 @@ quickcheck! {
}

fn binomial(n: usize, k: usize) -> usize {
if k > n {
0
} else {
(n - k + 1..=n).product::<usize>() / (1..=k).product::<usize>()
}
itertools::checked_binomial(n, k).unwrap()
}

quickcheck! {
Expand Down
18 changes: 13 additions & 5 deletions tests/test_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1138,11 +1138,19 @@ fn combinations_zero() {
}

fn binomial(n: usize, k: usize) -> usize {
if k > n {
0
} else {
(n - k + 1..=n).product::<usize>() / (1..=k).product::<usize>()
}
it::checked_binomial(n, k).unwrap()
}

#[test]
fn binomial_avoids_intermediate_overflow() {
// The naive "product then divide" formula overflows `usize` even when the
// binomial coefficient itself fits. C(21, 19) == C(21, 2) == 210, but
// (3..=21).product::<usize>() overflows on 64-bit. The same class of bug
// panics `combinations_inexact_size_hints` on 32-bit (#995): that test
// evaluates C(27, 7) because `Filter`'s size-hint upper bound is 18 and
// the lazy buffer has already loaded 9 items.
assert_eq!(binomial(21, 19), 210);
assert_eq!(binomial(27, 7), 888030);
}

#[test]
Expand Down
Loading