Java Implementation of Problem 20
View source code here on GitHub!
1/*
2Project Euler Problem 34
3
4This ended up being a filtering problem. The problem with my solution is that I
5am not satisfied with my filter at all. I feel like there is a more efficient
6way to go about it.
7
8Problem:
9
10145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
11
12Find the sum of all numbers which are equal to the sum of the factorial of
13their digits.
14
15Note: as 1! = 1 and 2! = 2 are not sums they are not included.
16*/
17package euler;
18
19public class p0020 implements IEuler {
20 @Override
21 public Object answer() {
22 long[] numbers = new long[11];
23 long ten16 = 10000000000000000L;
24 numbers[0] = 1;
25 for (byte i = 2; i <= 100; i++) {
26 for (byte j = 0; j < 10; j++)
27 numbers[j] *= i;
28 for (byte j = 0; j < 9; j++) {
29 if (numbers[j] > ten16) {
30 numbers[j + 1] += numbers[j] / ten16;
31 numbers[j] %= ten16;
32 }
33 }
34 }
35 long answer = 0;
36 long power = 1;
37 for (byte i = 0; i < 19; i++) {
38 for (byte j = 0; j < 10; j++)
39 answer += (numbers[j] / power) % 10;
40 power *= 10;
41 }
42 return (short) answer;
43 }
44}