patternjavaModerate
Finding the last ten digits of \$\sum_{n=1}^{1000} n^n\$
Viewed 0 times
lastthesum_digitsten1000finding
Problem
This is my solution to Project Euler Problem 48.
Problem:
The series, \$1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317\$ .
Find the last ten digits of the series, \$1^1 + 2^2 + 3^3 + ... + 1000^{1000}\$.
I would like feedback/advice to possibly increase efficiency and/or correct incorrect practices.
Problem:
The series, \$1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317\$ .
Find the last ten digits of the series, \$1^1 + 2^2 + 3^3 + ... + 1000^{1000}\$.
I would like feedback/advice to possibly increase efficiency and/or correct incorrect practices.
public static void main(String[] args) {
BigInteger start, sum = BigInteger.valueOf(0);
for (int i = 1; i <= 1000; i++) {
start = BigInteger.valueOf(i);
sum = sum.add(start.pow(i));
}
String sumStr = sum.toString();
System.out.println(sumStr.substring(sumStr.length() - 10));
}Solution
-
Use the right data type. The last ten digits of the sum is same as the sum modulo \$10000000000 = 10^{10}\$, which is smaller than \$2^{34}\$. All computations can be comfortably done with 64-bit integers; invoking
-
Reuse your computations. Once you computed \$k = n^n\$, use it to compute \$(2n)^{2n} = 2^{2n} n^{2n} = 2^{2n}k^2\$.
-
Devise an algorithm. The logic of the previous bullet applies to any \$mn\$: \$(mn)^{mn} = m^{mn}n^{mn} = (m^m)^n (n^n)^m\$. This observation lends itself to the scheduling of computations very close to be optimal. Think about divisibility in general and prime numbers in particular.
-
Any multiple of 10 raised to the corresponding power is surely divisible by \$10^{10}\$, and can be safely omitted from summation, but this is a minor optimization.
Use the right data type. The last ten digits of the sum is same as the sum modulo \$10000000000 = 10^{10}\$, which is smaller than \$2^{34}\$. All computations can be comfortably done with 64-bit integers; invoking
BigInteger is a definite overkill. Extracting ten digits via string operations is also quite suboptimal.-
Reuse your computations. Once you computed \$k = n^n\$, use it to compute \$(2n)^{2n} = 2^{2n} n^{2n} = 2^{2n}k^2\$.
-
Devise an algorithm. The logic of the previous bullet applies to any \$mn\$: \$(mn)^{mn} = m^{mn}n^{mn} = (m^m)^n (n^n)^m\$. This observation lends itself to the scheduling of computations very close to be optimal. Think about divisibility in general and prime numbers in particular.
-
Any multiple of 10 raised to the corresponding power is surely divisible by \$10^{10}\$, and can be safely omitted from summation, but this is a minor optimization.
Context
StackExchange Code Review Q#143942, answer score: 10
Revisions (0)
No revisions yet.