Project Euler #30
Project Euler problem 30 states:
Surprisingly there are only three numbers that can be written as the sum
of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth
powers of their digits.
I used the algorithm below to solve 4th power digits and it worked.
Somehow, it doesn't seem to produce the right answer for 5th power digits.
Can anyone help me spot what I'm missing?
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Problem26 {
static Map<Integer, Integer> table = new HashMap<>();
public static void main(String[] args) {
populateTable();
int runningTotal = 0;
for(Entry<Integer, Integer> entry : table.entrySet ()) {
if(entry.getKey().equals(entry.getValue())) {
System.out.println(entry);
runningTotal += entry.getKey();
}
}
System.out.println(runningTotal);
}
static void populateTable() {
for (int i = 1; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 10; k++) {
for (int l = 0; l < 10; l++) {
for(int m = 0; m < 10; m++) {
final Integer key = Integer.parseInt(i+ "" +j+
"" +k+ "" +l+ "" +m);
final Integer value = (int) Math.pow(i, 5) +
(int) Math.pow(j, 5) + (int) Math.pow(k, 5) +
(int) Math.pow(l, 5) +
(int)Math.pow(m, 5);
table.put(key, value);
}
}
}
}
}
}
}
No comments:
Post a Comment