Skip to content

Instantly share code, notes, and snippets.

@cruxrebels
Created April 26, 2016 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cruxrebels/033ef092d05c8c7b2c43d4eb72165872 to your computer and use it in GitHub Desktop.
Save cruxrebels/033ef092d05c8c7b2c43d4eb72165872 to your computer and use it in GitHub Desktop.
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…
bool isPrime(int n)
{
for(int i=2; i*i<=n; ++i)
{
if(n%i==0)
return false;
}
return true;
}
vector<int> Solution::primesum(int A) {
vector<int> result;
if(A<3)
return result;
vector<bool> arr(A+1, 0); //vector<int> causes judge memory overflow.
for (int i=2; i<=A; ++i)
{
if(arr[i]==0)
{
//prime.emplace_back(i);
if(isPrime(A-i))
{
result.emplace_back(i);
result.emplace_back(A-i);
break;
}
for(int j=i; i*j<=A; ++j)
arr[i*j] = 1;
}
}
return result;
}
@rajeshsahu09
Copy link

rajeshsahu09 commented Jul 16, 2019

this could be one
`int is_prime(int p) {
int prime = 1;
for(int i = 2; i < p/2; i++){
if(p%i == 0) prime = 0;
}
if(prime) return 1;
else return 0;
}
vector Solution::primesum(int A) {
vector res;
if(A <= 3) return res;

int diff = 0;
for(int i = 2; i < A; i++) {
    if(is_prime(i)) {
        diff = A - i;
        if(is_prime(diff)) {
            res.push_back(i);
            res.push_back(diff);
            break;
        }
    }
}
return res;

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment