forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p027.java
43 lines (35 loc) · 894 Bytes
/
p027.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
/*
* Solution to Project Euler problem 27
* By Nayuki Minase
*
* http://nayuki.eigenstate.org/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p027 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p027().run());
}
public String run() {
int bestNum = -1;
int bestA = -1;
int bestB = -1;
for (int a = -1000; a <= 1000; a++) {
for (int b = -1000; b <= 1000; b++) {
int num = numberOfConsecutivePrimesGenerated(a, b);
if (bestNum == -1 || num > bestNum) {
bestNum = num;
bestA = a;
bestB = b;
}
}
}
return Integer.toString(bestA * bestB);
}
private static int numberOfConsecutivePrimesGenerated(int a, int b) {
for (int i = 0; ; i++) {
int n = i * i + i * a + b;
if (n < 0 || !Library.isPrime(n))
return i;
}
}
}