forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p225.java
87 lines (64 loc) · 1.45 KB
/
p225.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* Solution to Project Euler problem 225
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p225 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p225().run());
}
private static final int INDEX = 124; // 1-based
public String run() {
int count = 0;
for (int i = 1; ; i += 2) {
if (!hasMultiple(i)) {
count++;
if (count == INDEX)
return Integer.toString(i);
}
}
}
private static boolean hasMultiple(int modulus) {
// Floyd's cycle-finding algorithm
Tribonacci slow = new Tribonacci(modulus);
Tribonacci fast = new Tribonacci(modulus);
while (true) {
if (slow.hasMultiple())
return true;
slow.next();
fast.next();
fast.next();
if (slow.equals(fast))
return false;
}
}
private static class Tribonacci {
public final int modulus;
public int a;
public int b;
public int c;
public Tribonacci(int mod) {
a = 1 % mod;
b = 1 % mod;
c = 1 % mod;
modulus = mod;
}
public void next() {
int d = (a + b + c) % modulus;
a = b;
b = c;
c = d;
}
public boolean hasMultiple() {
return a == 0 || b == 0 || c == 0;
}
public boolean equals(Tribonacci other) {
return a == other.a
&& b == other.b
&& c == other.c
&& modulus == other.modulus;
}
}
}