Browse Source

Math: assert valid binomialCoefficient() input instead of returning 0.

pull/435/merge
Vladimír Vondruš 6 years ago
parent
commit
f225497475
  1. 3
      src/Magnum/Math/Functions.cpp
  2. 13
      src/Magnum/Math/Test/FunctionsTest.cpp

3
src/Magnum/Math/Functions.cpp

@ -45,7 +45,8 @@ UnsignedInt log2(UnsignedInt number) {
}
UnsignedLong binomialCoefficient(const UnsignedInt n, UnsignedInt k) {
if(k > n) return 0;
CORRADE_ASSERT(n >= k,
"Math::binomialCoefficient(): k can't be greater than n in (" << Corrade::Utility::Debug::nospace << n << "choose" << k << Corrade::Utility::Debug::nospace << ")", {});
/* k and n - k gives the same value, optimize the calculation to do fewer
steps */

13
src/Magnum/Math/Test/FunctionsTest.cpp

@ -55,6 +55,7 @@ struct FunctionsTest: Corrade::TestSuite::Tester {
void fmod();
void binomialCoefficient();
void binomialCoefficientInvalidInput();
void binomialCoefficientOverflow();
void sqrt();
@ -120,6 +121,7 @@ FunctionsTest::FunctionsTest() {
&FunctionsTest::fmod,
&FunctionsTest::binomialCoefficient,
&FunctionsTest::binomialCoefficientInvalidInput,
&FunctionsTest::binomialCoefficientOverflow,
&FunctionsTest::sqrt,
@ -310,6 +312,17 @@ void FunctionsTest::binomialCoefficient() {
CORRADE_COMPARE(Math::binomialCoefficient(62, 31), 465428353255261088ull);
}
void FunctionsTest::binomialCoefficientInvalidInput() {
#ifdef CORRADE_NO_ASSERT
CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions");
#endif
std::ostringstream out;
Error redirectError{&out};
Math::binomialCoefficient(15, 16);
CORRADE_COMPARE(out.str(), "Math::binomialCoefficient(): k can't be greater than n in (15 choose 16)\n");
}
void FunctionsTest::binomialCoefficientOverflow() {
#ifdef CORRADE_NO_ASSERT
CORRADE_SKIP("CORRADE_NO_ASSERT defined, can't test assertions");

Loading…
Cancel
Save