【问题标题】:Print Last Ten Digits of a BigInteger打印 BigInteger 的最后十位数字
【发布时间】:2017-07-25 04:51:58
【问题描述】:

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

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

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);


    }

}

我们不胜感激。

【问题讨论】:

    标签: biginteger


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

    • 谢谢,这很好用,唯一的问题是最终结果是相反的。最后 10 位数字是 9110846700。将您的代码添加到我自己的代码后,我得到 0076480119。我只需要想办法将它反转,这样就可以完美地工作。
    • @shockemc 你可以从i = numberLength-10;i&lt;numberLength;i++ 迭代来做同样的事情。希望有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 2014-04-20
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多