forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp074.java
More file actions
52 lines (39 loc) · 1.07 KB
/
p074.java
File metadata and controls
52 lines (39 loc) · 1.07 KB
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
/*
* Solution to Project Euler problem 74
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.util.HashSet;
import java.util.Set;
public final class p074 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p074().run());
}
private static final int LIMIT = Library.pow(10, 6);
public String run() {
int count = 0;
for (int i = 0; i < LIMIT; i++) {
if (getChainLength(i) == 60)
count++;
}
return Integer.toString(count);
}
private static int getChainLength(int n) {
Set<Integer> seen = new HashSet<>();
while (true) {
if (!seen.add(n))
return seen.size();
n = factorialize(n);
}
}
// Hard-coded values for factorial(0), factorial(1), ..., factorial(9)
private static int[] FACTORIAL = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
private static int factorialize(int n) {
int sum = 0;
for (; n != 0; n /= 10)
sum += FACTORIAL[n % 10];
return sum;
}
}