使用长参数来使用 BigInteger 的重构函数

Refactoring function that uses long argument to use BigInteger

我需要转换一些使用 long 参数的方法,事实证明 64 位 longs 对我需要的来说太小了,我所做的是转换这些以便它们可以使用BigInteger.

这是可重现的例子:

原文:

static void ConditionalSum_1(long n) {

    long soma = 0;
 
    int i = 1;
    while (i < n) {
        for (int j = 0; j < i; j++) {
            soma++;
        }
        i *= 2;
    }
    System.out.println("Soma C1 = " + soma);
}

已转换:

static void ConditionalSum_2(BigInteger n) {

    BigInteger soma = BigInteger.ZERO;

    BigInteger i = BigInteger.ONE;
    while (i.compareTo(n) < 0) {
        for (BigInteger j = BigInteger.ZERO; j.compareTo(i) < 0; j.add(BigInteger.ONE)) {
            soma.add(BigInteger.ONE);
        }
        i.multiply(BigInteger.TWO);
    }
    System.out.println("Soma C2 = " + soma);
}

函数调用:

public static void main(String[] args) {

    ConditionalSum_1(999999L); //works fine
    ConditionalSum_2(new BigInteger("999999")); //infinite loop

}

由于我无法确定的原因,ConditionalSum_2 函数似乎没有工作,没有抛出异常,变量似乎没有改变,因此例程进入了一个无限循环。

我是 Java 的新手,所以我确信我在这里遗漏了一些基本知识。将不胜感激。

当您将一个 BigInteger 与另一个 BigInteger 相加时,总和将作为结果 returned。因此,您必须再次将 return 值分配给适当的变量。

   for (BigInteger j = BigInteger.ZERO; j.compareTo(i) < 0; j = j.add(BigInteger.ONE)) 
   {
        soma = soma.add(BigInteger.ONE);
   }

   i = i.multiply(BigInteger.TWO);