-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimePairsWithTargetSum.java
More file actions
51 lines (50 loc) · 1.22 KB
/
Copy pathPrimePairsWithTargetSum.java
File metadata and controls
51 lines (50 loc) · 1.22 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PrimePairsWithTargetSum {
int N = 1000000;
int[] prime = new int[N];
public void sieve() {
Arrays.fill(prime, 1);
prime[0] = 0;
prime[1] = 0;
for (int i = 2; i * i < N; i++) {
if (prime[i] == 1) {
for (int j = i * i; j < N; j += i) {
prime[j] = 0;
}
}
}
}
public List<List<Integer>> findPrimePairs(int n) {
sieve();
List<List<Integer>> ans = new ArrayList<>();
int l = 2;
int r = n - 1;
while (l <= r) {
if (prime[l] == 0) {
l++;
continue;
}
if (prime[r] == 0) {
r--;
continue;
}
if (l + r == n) {
List<Integer> temp = new ArrayList<>();
temp.add(l);
temp.add(r);
ans.add(temp);
l++;
r--;
}
else if (l + r < n) {
l++;
}
else {
r--;
}
}
return ans;
}
}