如何计算高于限制的数字,并使用 BigInteger

How calculate number higher than limit, and use BigInteger

下面的代码计算 2^15 和工作的数字的总和。如果我将 for 循环条件更改为 15,则 d2 变为 2^16。 --> 我想要 2^15。 然后我把它改成999,数字和不匹配。 (总数:1189)

还有其他方法吗?

public void go()
{           
    int sum = 0;
    BigInteger d2 = BigInteger.ONE.add(BigInteger.ONE);
    BigInteger two = d2;

    for(int i = 0; i < 14; i++)
    {
        System.out.println(d2);
        d2 = d2.multiply(two);
    }

    System.out.println("\n" + d2);

    double val = d2.doubleValue();
    double temp = val;
    while(val > 0)
    {
        temp = val % 10;
        val /= 10;
        sum += temp;
        System.out.println(temp);
    }

    System.out.println("Sum: " + sum);

}

你切换到 double 来计算数字的和,当它看起来像 BigInteger.divideAndRemainder 是你需要的。

你会得到类似的东西:

temp = d2;

while (temp.compareTo(BigInteger.ZERO) > 0) {           
    BigInteger[] divideAndRemainder = temp.divideAndRemainder(BigInteger.valueOf(10));
    temp = divideAndRemainder[0];
    sum = sum.add(divideAndRemainder[1]);
}