java - 如何使用 biginteger 对两个边界之间的数字求和
问题描述
我试图总结 2 个给定数字之间的所有数字,不包括边界。例如addNumbers("5", "8")
,由于 6+7=13,应该返回 13。这是我目前拥有的功能。
public static BigInteger addNumbers(String from, String to) {
BigInteger total = new BigInteger("0");
BigInteger startingBoundary = new BigInteger(from);
BigInteger finishingBoundary = new BigInteger(to);
if (startingBoundary.compareTo(finishingBoundary) < 0) {
startingBoundary = new BigInteger(from);
finishingBoundary = new BigInteger(to);
} else {
finishingBoundary = new BigInteger(from);
startingBoundary = new BigInteger(to);
}
while (startingBoundary.compareTo(finishingBoundary) != 0 ) {
System.out.println("Starting boundary:" + startingBoundary.intValue());
System.out.println("Finishing boundary: " + finishingBoundary.intValue());
total.add(startingBoundary);
System.out.println("total: "+total.intValue());
startingBoundary.add(new BigInteger("1"));
}
return total;
}
问题是尽管我改变了它的值,while 条件似乎在无限运行。此外,当在每个循环中打印出总对象时,它总是打印出 0。我知道我将它初始化为 0,但我希望它会在我添加到它时发生变化..
解决方案
请注意,使用BigInteger
意味着数字以及两个数字之间的差异可能很大。从字面上看,从下边界循环到上边界可能需要很长时间。相反,您可以使用封闭形式的变体sum(1..N) = (N*(N+1))/2
。用它来对 from 1
toupper
和 from 1
to的数字求和lower
,然后将两者结合起来得到你想要的结果。
BigInteger lower = new BigInteger("5");
BigInteger upper = new BigInteger("8");
BigInteger one = BigInteger.ONE, two = BigInteger.TWO;
BigInteger oneToUpper = upper.multiply(upper.add(one)).divide(two);
BigInteger oneToLower = lower.multiply(lower.add(one)).divide(two);
BigInteger lowertoUpperInc = oneToUpper.subtract(oneToLower).add(lower);
System.out.println(lowertoUpperInc); // 5 + 6 + 7 + 8 = 26
BigInteger lowertoUpperExc = oneToUpper.subtract(oneToLower).subtract(upper);
System.out.println(lowertoUpperExc); // 6 + 7 = 13
(请注意,对于此示例,您的循环似乎也返回18
了,这似乎是您真正想要的5+6+7
,因此不是您真正想要的。)
除了你的循环,这也适用于真正 BigInteger
的,例如和分别为lower = 123456789123456789
和的总和(包括和不包括) 。upper = 987654321987654321
480109740480109740075445815075445815
480109740480109738964334703964334705
推荐阅读
- jquery - 无法访问 json 对象中可验证的 jquery
- php - Joomla 如何从外部脚本调用控制器
- android - 什么是好方法,InflateView/removeView 或设置 Visibility.GONE?
- javascript - JavaScript:未调用“forEach”的引用
- c++ - 无法从 C++ 启动可执行文件
- python - Anaconda 安装弄乱了现有的 Python 包
- android - 使用 Adapter 将数据绑定到 RecyclerView 时出现问题。没有看到模型类
- java - XSD 在使用导入验证 xsd 期间忽略命名空间
- c# - 如何在两个字典之间获取除外
>? - javascript - 将HTML转换为图像时如何显示图像