This is an automated email from the ASF dual-hosted git repository. aherbert pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-math.git
commit fc239a64be75066a1ab07bfae273ffcc5902fa7e Author: aherbert <aherb...@apache.org> AuthorDate: Mon Oct 31 11:08:52 2022 +0000 Fix overflow bug in stirlingS2 when n > 64, k = 2 --- .../java/org/apache/commons/math4/legacy/util/CombinatoricsUtils.java | 4 ++++ .../org/apache/commons/math4/legacy/util/CombinatoricsUtilsTest.java | 3 +++ 2 files changed, 7 insertions(+) diff --git a/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/util/CombinatoricsUtils.java b/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/util/CombinatoricsUtils.java index 7e07fa034..e4e9c679b 100644 --- a/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/util/CombinatoricsUtils.java +++ b/commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/util/CombinatoricsUtils.java @@ -101,6 +101,10 @@ public final class CombinatoricsUtils { } else if (k == 1 || k == n) { return 1; } else if (k == 2) { + if (n > 64) { + throw new MathArithmeticException(LocalizedFormats.ARGUMENT_OUTSIDE_DOMAIN, + n, 0, stirlingS2.length - 1); + } return (1L << (n - 1)) - 1L; } else if (k == n - 1) { return BinomialCoefficient.value(n, 2); diff --git a/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/util/CombinatoricsUtilsTest.java b/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/util/CombinatoricsUtilsTest.java index e1fbe8880..19e5d8a59 100644 --- a/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/util/CombinatoricsUtilsTest.java +++ b/commons-math-legacy/src/test/java/org/apache/commons/math4/legacy/util/CombinatoricsUtilsTest.java @@ -82,5 +82,8 @@ public class CombinatoricsUtilsTest { @Test public void testStirlingS2Overflow() { Assertions.assertThrows(MathArithmeticException.class, () -> CombinatoricsUtils.stirlingS2(26, 9)); + + Assertions.assertEquals(9223372036854775807L, CombinatoricsUtils.stirlingS2(64, 2)); + Assertions.assertThrows(MathArithmeticException.class, () -> CombinatoricsUtils.stirlingS2(65, 2)); } }