I am writing a program to calculate:
1^1 + 2^2 + 3^3 + ... + 1000^1000 = ?
Once it has calculated it I want to remove all of the digits in the answer besides the last ten digits, and then print the final ten digits on the screen. To remove all of the other digits I am using the StringBuilder.deleteCharAt()
method, however, this is causing me some problems. I have provided my code below:
import java.math.BigInteger;
public class problemFourtyEight {
public static void main(String [] args) {
BigInteger answer = new BigInteger(""+0);
for(int i = 0; i <= 1000; i++) {
BigInteger temp = new BigInteger(""+i);
temp = temp.pow(i);
answer = answer.add(temp);
}
System.out.println(answer.toString().length());
StringBuilder sb = new StringBuilder((answer.toString()));
for(int k = 0; k <= (answer.toString().length() - 10); k++) {
sb.deleteCharAt(k); //Line 13 is here.
}
String finalAnswer = sb.toString();
System.out.println(finalAnswer);
}
}
The exception thrown is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1501
at java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:797)
at java.lang.StringBuilder.deleteCharAt(StringBuilder.java:253)
at problemFourtyEight.main(problemFourtyEight.java:13)
From printing out the length of the answer (before removing any characters), it tells me the length of the number is 3001, so I can't understand why the String index
1,501 is said to be OutOfBounds
.