打印 BigInteger 的最后十位数字

Print Last Ten Digits of a BigInteger

我有一些基本代码可以解决项目 Euler 上的问题,确切地说是第 48 个问题。虽然它在技术上产生了答案,但我希望我的程序能够整齐地呈现答案,因此我想将最后十位数字打印到控制台并省略其他所有内容。

我看到一些 post 建议人们对原始数据类型使用模运算符,虽然我不知道为什么返回余数可以作为解决方案,但我还是尝试了,但无济于事.

System.out.println(GrandTotal.mod(BigInteger.TEN));

Gets last digit of a number

导入java.math.BigInteger;

public class eulerNo48 {

    public static void main(String[] args)
    {

        /**
         * Loop that calculates the each number from 1 to 1000 to the 
         * power of itself and sums the results.
         */

        BigInteger sum = BigInteger.ZERO;  
        BigInteger tempVar = BigInteger.ONE;
        BigInteger GrandTotal = BigInteger.ZERO;

        for (int i = 1; i <= 1000; i++) {
            sum = tempVar.pow(i); // Calculates the value of tempVar(1 - 1000) to its respective power (i).
            tempVar = tempVar.add(BigInteger.ONE); // Increments temVar for each iteration of the loop.
            GrandTotal = GrandTotal.add(sum); // Adds sum to the grand total.
        }


        System.out.println(GrandTotal);


    }

}

感谢您提供的所有帮助。

转换为字符串并与之一起工作可能会有所帮助 -

String digits = bigInteger.toString(); // replace bigInteger with GrandTotal in your case
int numberLength = digits.length();
for(int i = numberLength ; i > numberLength - 10; i--) {
    int digit = digits.charAt(i-1) - '0';
    System.out.print(digit);
}