-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path_10394_TwinPrimes.java
64 lines (52 loc) · 1.59 KB
/
_10394_TwinPrimes.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
package io.github.tahanima.uva;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author tahanima
*/
public class _10394_TwinPrimes {
static final int MAX = 20000001;
static final ArrayList<Pair> twinPrimes = new ArrayList<>();
static final class Pair {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
public static void computeTwinPrimes() {
final boolean[] prime = new boolean[MAX];
int sqrt = (int) Math.sqrt(MAX);
for (int i = 3; i <= sqrt; i += 2) {
if (!prime[i]) {
for (int j = i * i; j < MAX; j += (i + i)) {
prime[j] = true;
}
}
}
int previous = 2;
for (int i = 3; i < MAX; i += 2) {
if (!prime[i]) {
if (i == (previous + 2)) {
twinPrimes.add(new Pair(previous, i));
}
previous = i;
}
}
}
public static void main(String[] args) {
computeTwinPrimes();
Scanner scanner = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext()) {
int n = scanner.nextInt();
stringBuilder.append("(")
.append(twinPrimes.get(n - 1).first)
.append(", ")
.append(twinPrimes.get(n - 1).second)
.append(")\n");
}
System.out.print(stringBuilder);
}
}