-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprimeSum.java
More file actions
58 lines (43 loc) · 1.31 KB
/
Copy pathprimeSum.java
File metadata and controls
58 lines (43 loc) · 1.31 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
52
53
54
55
56
57
58
/*
Given an even number ( greater than 2 ), return two prime numbers whose sum will be equal to given number.
NOTE A solution will always exist. read Goldbach’s conjecture
Example:
Input : 4
Output: 2 + 2 = 4
If there are more than one solutions possible, return the lexicographically smaller solution.
If [a, b] is one solution with a <= b,
and [c,d] is another solution with c <= d, then
[a, b] < [c, d]
If a < c OR a==c AND b < d. */
public class Solution {
public ArrayList<Integer> primesum(int A) {
ArrayList<Integer> ans = new ArrayList<>();
boolean prime[] = new boolean[A+1];
Set<Integer> s = new HashSet<>();
for(int i=0;i<=A;i++){
prime[i] = true;
}
prime[0] = false;
prime[1] = false;
for(int i = 2;i*i<=A;i++){
if(prime[i]){
for(int j = 2*i;j<=A;j +=i){
prime[j] = false;
}
}
}
for(int i = 2;i<=A;i++){
if(prime[i]){
s.add(i);
}
}
for (int i=2;i<=A;i++) {
if(s.contains(i) && s.contains(A-i)){
ans.add(i);
ans.add(A-i);
break;
}
}
return ans;
}
}