首页 > 解决方案 > 如何使用 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,但我希望它会在我添加到它时发生变化..

标签: javabiginteger

解决方案


请注意,使用BigInteger意味着数字以及两个数字之间的差异可能很大从字面上看,从下边界循环到上边界可能需要很长时间。相反,您可以使用封闭形式的变体sum(1..N) = (N*(N+1))/2。用它来对 from 1toupper和 from 1to的数字求和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 = 987654321987654321480109740480109740075445815075445815480109740480109738964334703964334705


推荐阅读