mirror of
https://gitee.com/dromara/hutool.git
synced 2026-02-09 09:16:26 +08:00
Merge pull request #4174 from ZhonglinGui/v5-dev
修复MathUtil.multiple 方法在大整数乘法运算中整数溢出风险
This commit is contained in:
@@ -1692,7 +1692,15 @@ public class NumberUtil {
|
||||
* @return 最小公倍数
|
||||
*/
|
||||
public static int multiple(int m, int n) {
|
||||
return m * n / divisor(m, n);
|
||||
// 先计算最大公约数
|
||||
int gcd = divisor(m, n);
|
||||
// 使用长整型避免溢出,再转换回整型
|
||||
long result = (long) m / gcd * (long) n;
|
||||
// 检查结果是否在int范围内
|
||||
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
|
||||
throw new ArithmeticException("Integer overflow: " + m + " * " + n + " / " + gcd);
|
||||
}
|
||||
return (int) result;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -706,6 +706,18 @@ public class NumberUtilTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleOverflow() {
|
||||
int a = 500000;
|
||||
int b = 600000;
|
||||
|
||||
// 原方法使用 a * b / gcd(a, b) 计算,a * b 会先溢出,得到最小公倍数为负数
|
||||
// 使用修改后的multiple方法,测试它是否能正确处理这种情况
|
||||
int result = NumberUtil.multiple(a, b);
|
||||
// 验证结果必须是正数(两个正数的最小公倍数必须为正)
|
||||
assertTrue(result > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFloatBinaryStr() {
|
||||
// 获取浮点数的 IEEE 754 原始比特位字符串
|
||||
final String result = NumberUtil.getBinaryStr(3.5);
|
||||
|
||||
Reference in New Issue
Block a user