forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p026.java
48 lines (37 loc) · 978 Bytes
/
p026.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
/*
* Solution to Project Euler problem 26
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
import java.util.HashMap;
import java.util.Map;
public final class p026 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p026().run());
}
public String run() {
int bestNumber = -1;
int bestLength = -1;
for (int i = 1; i <= 1000; i++) {
int len = getCycleLength(i);
if (bestLength == -1 || len > bestLength) {
bestNumber = i;
bestLength = len;
}
}
return Integer.toString(bestNumber);
}
private static int getCycleLength(int n) {
Map<Integer,Integer> stateToIter = new HashMap<Integer,Integer>();
int state = 1;
int iter = 0;
while (!stateToIter.containsKey(state)) {
stateToIter.put(state, iter);
state = state * 10 % n;
iter++;
}
return iter - stateToIter.get(state);
}
}