如何使用 biginteger 对两个边界之间的数字求和

egh*_*ghe 0 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;
Run Code Online (Sandbox Code Playgroud)

}

问题是尽管我改变了它的值,但 while 条件似乎无限运行。此外,在每个循环中打印出总对象时,它总是打印出 0。我知道我将它初始化为 0,但我希望它在我添加时会发生变化。

tob*_*s_k 5

请注意,使用BigInteger意味着这些数字以及两个数字之间的差异可能很大。从下边界到上边界循环可能需要很长时间,从字面上看。相反,您可以使用封闭形式的变体sum(1..N) = (N*(N+1))/2。用它来总结的数量1upper1lower,然后将二者结合起来,以获得您想要的结果。

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
Run Code Online (Sandbox Code Playgroud)

(请注意,您的循环似乎也在18此示例中返回,这似乎5+6+7是您真正想要的,因此不是您真正想要的。)

除了你的循环,这也将努力为真正的 BigInteger,如资金(包括和不包括)对lower = 123456789123456789upper = 987654321987654321480109740480109740075445815075445815480109740480109738964334703964334705分别。