-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem34.java
53 lines (38 loc) · 1.4 KB
/
Problem34.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package problem;
import utils.data.DigitNumber;
import utils.operator.Factorial;
import java.util.stream.IntStream;
import static java.lang.Math.toIntExact;
import static problem.Solution.problem;
public class Problem34 {
public static void main(String[] args) {
// https://projecteuler.net/problem=34
problem("Digit factorials",
Problem34::sumOfNumbersWhereTheSumOfItsDigitsEqualsItself);
}
private static final int[] FACTORIALS = makeFactorials();
private static int sumOfNumbersWhereTheSumOfItsDigitsEqualsItself() {
return IntStream.rangeClosed(10, guessMax())
.filter(Problem34::doesSumOfFactorialsOfDigitsEqualsItself)
.sum();
}
private static int guessMax() {
return (int) (FACTORIALS[9] * Math.ceil(Math.log10(FACTORIALS[9])) + 1);
}
static boolean doesSumOfFactorialsOfDigitsEqualsItself(int i) {
return (sumOfFactorialsOfDigits(i) == i);
}
private static int[] makeFactorials() {
int[] factorials = new int[10];
for (int i = 0; i < factorials.length; i++)
factorials[i] = toIntExact(Factorial.of(i));
return factorials;
}
private static long sumOfFactorialsOfDigits(int i) {
long sum = 0;
for (int d : DigitNumber.of(i).digits())
sum += FACTORIALS[d];
return sum;
}
private Problem34() {}
}