Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000
I'm using Java.. I think I can modpow function for this question. (BigInteger) Here is my Java code but it isnt work. How can I do that?
public static void main(String[] args) {
BigInteger a;
BigInteger b = null;
BigInteger c = new BigInteger("10000000000");
for (int i = 0; i <= 1000; i++) {
a = new BigInteger("" + i);
b.add(a.modPow(a, c));
}
System.out.println(b);
}
I get the error of NullPointerException.. Sorry my english, thanks.
BigInteger b = null;
therefore, in the first iteration, when you do b.add(a.modPow(a, c));
, b
is null
I think you have two basic errors, first you never initialized b
- that could be
BigInteger b = BigInteger.ZERO;
Then you need to assign the result of the b.add(a.modPow(a, c));
to b
(since BigInteger add doesn't modify in-place). That is,
b = b.add(a.modPow(a, c));
When I make those two changes I get the output
4629110846701
null
is not a zero value. Initialize your variable with 0
like this
BigInteger b = new BigInteger("0");
Even if, as peter.petrov said, this problem could be solved with one more simple solution without using big integers
import java.math.BigInteger;
class Main {
public static void main(String[] args) {
BigInteger num = BigInteger.ZERO;
for (int i = 1; i <= 1000; i++) {
num = num.add(BigInteger.valueOf(i).pow(i));
}
BigInteger res = num.mod(new BigInteger("10000000000"));
System.out.println(res);
}
}
output :
9110846700
More efficient solution taken from http://www.mathblog.dk/project-euler-48-last-ten-digits/ as biginteger gets very slow on very large numbers
import java.io.InputStream;
class Main {
public static void main(String[] args) {
long result = 0;
long modulo = 10000000000L;
for (int i = 1; i <= 1000; i++) {
long temp = i;
for (int j = 1; j < i; j++) {
temp *= i;
temp %= modulo;
}
result += temp;
result %= modulo;
}
System.out.println(result);
}
output :
9110846700
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.