1

I have some basic code that solves a problem on project Euler, number 48 to be exact. Although it technically produces the answer I'd like my program to present the answer neatly, as such I'd like to print the last TEN digits to the console and omit everything else.

I've seen a couple of post suggesting that people use modulo operator on primitive data types and though I have no idea why returning a remainder could work as a solution I tried it anyway, to no avail.

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

Gets last digit of a number

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


    }

}

Any and all help is appreciated.

Community
  • 1
  • 1
shockemc
  • 85
  • 1
  • 10

1 Answers1

0

Converting to string and working alongwith might help -

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);
}
Naman
  • 27,789
  • 26
  • 218
  • 353
  • 1
    Thank you, this works well, the only problem being that the end result is reversed. The last 10 digits are 9110846700. After adding your code to my own I get 0076480119. I just need to think of way to inverse it and this would work perfectly. – shockemc Mar 06 '17 at 12:43
  • @shockemc you can iterate from `i = numberLength-10;i – Naman Mar 06 '17 at 12:44