-
Notifications
You must be signed in to change notification settings - Fork 56
/
PrimeSum.cpp
73 lines (44 loc) · 1.17 KB
/
PrimeSum.cpp
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
65
66
67
68
69
70
/*
https://www.interviewbit.com/problems/Prime-Sum/
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.
*/
vector<int> Solution::primesum(int A)
{
if(A<3) return vector<int>();
vector<bool> prime(A+1); int a,b;
// Sieve Of Eratosthenes
prime[0] = prime[1] = false;
for (int i=2; i<=A; i++)
prime[i] = true;
for(int i=2;i*i<=A;i++)
{
if(prime[i])
{
for(int j=i*2;j<=A;j+=i)
{
prime[j]=false;
}
}
}
// Real task
for(int i=0;i<A;i++)
{
if(prime[i] and prime[A-i])
{
a=i; b=A-i;
break;
}
}
vector<int> res;
res.push_back(a); res.push_back(b);
return res;
}