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.
Approach : Use Sieve of Eratosthenes to find all the prime numbers and then check if i and n - i is set, return i & n - i. */
#include <iostream>
#include <cmath>
using namespace std;
int *allPrimes(int N){
int *arr = new int[N + 1];
arr[0] = 0;
arr[1] = 0;
for(int i = 2; i <= N; i++){
arr[i] = 1;
}
for(int i = 2; i <= sqrt(N); i++){
if(arr[i]){
for(int j = i * i; j <= N; j = j + i){
arr[j] = 0;
}
}
}
return arr;
}
int main(){
//should be prime
int N = 20;
int *arr = new int[N + 1];
arr = allPrimes(N);
for(int i = 2; i <= N; i++){
if(arr[i] && arr[N - i]){
cout << i << " " << N - i << endl;
}
}
return 0;
}
please write code in c.
ReplyDeleteI prefer to write in cpp. I provide the approach in the posts and you can use it to write the code in any language you prefer.
Delete