C++ solution | Simple Solution


#1

bool isPrime(int n){

if(n<=1){
    return false;
}
if(n==2 || n == 3){
    return true;
}

if(n%2==0 || n%3==0){
  return false;  
}

for(int i=5;i*i<=n;i=i+6){
    if(n%i==0 || n%(i+2)==0){
        return false;
    }
}
return true;

}

vector Solution::primesum(int n) {

vector<int> v;
for(int i=2;i<n;i++){
    for(int j=2;j<n;j++){
        
        
            if((i+j)==n){
                
              if(isPrime(i) && isPrime(j)){
                    
              v.push_back(i);
              v.push_back(j);
              return v;
            }
        }
    }
}
return v;

}


#3

Taking two loops for i and j respectively makes the prime sum function to be O(n^2) * the time complexity of isPrime() function.
A better way would be to use :
for(int i=2 ; i <= n/2 ; i ++)
if (isPrime(i) && isPrime(n-i))
This will do it in O(n) time complexity for the primesum function * the time complexity of isPrime() function.


#4

we can optimize more as we know both number will be always odd except for 4;
so we can do with i=i+2; from 3