forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p046.java
46 lines (34 loc) · 873 Bytes
/
p046.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
/*
* Solution to Project Euler problem 46
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p046 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p046().run());
}
public String run() {
for (int i = 2; ; i++) {
if (!satisfiesConjecture(i))
return Integer.toString(i);
}
}
private boolean satisfiesConjecture(int n) {
if (n % 2 == 0 || isPrime(n))
return true;
// Now n is an odd composite number
for (int i = 1; i * i * 2 <= n; i++) {
if (isPrime(n - i * i * 2))
return true;
}
return false;
}
private boolean[] isPrime = {};
private boolean isPrime(int n) {
if (n >= isPrime.length)
isPrime = Library.listPrimality(n * 2);
return isPrime[n];
}
}