-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProblem_026.java
More file actions
52 lines (43 loc) · 1.2 KB
/
Problem_026.java
File metadata and controls
52 lines (43 loc) · 1.2 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
package euler;
import java.util.HashMap;
public class Problem_026 {
static int longestReciprocalCylce() {
return longestReciprocalCylce(1000);
}
private static int longestReciprocalCylce(int upperbound) {
int longestDiv = 0;
String longestCycle = "";
for(int div = 2; div < upperbound; div++) {
String currentCycle = getReciprocalCycle(div);
if(longestCycle.length() < currentCycle.length()) {
longestCycle = currentCycle;
longestDiv = div;
}
}
// System.out.println(longestCycle);
return longestDiv;
}
private static String getReciprocalCycle(int div) {
HashMap<Integer, Integer> numerators = new HashMap<Integer, Integer>();
numerators.put(1, 0);
String decimal = "";
int num = 1, index = 1;
boolean cycleFound = false;
while(! cycleFound) {
if(num == 0) return ""; // decimal terminates
int fraction = num / div;
if(fraction == 0) {
num *= 10;
} else {
num %= div;
decimal += fraction;
if(numerators.containsKey(num)) { // numerator is about to be reused
cycleFound = true;
decimal = decimal.substring(numerators.get(num), decimal.length());
}
numerators.put(num, index++);
}
}
return decimal;
}
}