Given an even number (greater than 2), return two prime numbers whose sum will be equal to the given number.
A solution will always exist.
Input: 4
Output: 2 + 2 = 4
Example:
Input: N=20
Output: 3 17
Approach
C++
#include <bits/stdc++.h>using namespace std;vector<int> allPrimes(int N){vector<int> arr(N+1,0);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(){int N = 20;vector<int> arr(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;}
No comments:
Post a Comment