A prime number greater than 2 is odd, while 2 is the only even prime number. This property can be used to efficiently determine whether a given prime number can be represented as the sum of two prime numbers.
- For an odd prime N, one of the two prime numbers must be 2.
- Therefore, we only need to check whether N - 2 is also prime.
Illustration
Input: N = 13
Output: YesExplanation: 13 = 11 + 2, and both 11 and 2 are prime.
Input: N = 11
Output: NoExplanation: 11 - 2 = 9, which is not prime, so 11 cannot be expressed as the sum of two prime numbers.
Approach
The efficient approach uses the fact that every prime number except 2 is odd.
- Check whether N is prime.
- Compute N - 2.
- Check whether N - 2 is prime.
- If both are prime, N can be expressed as 2 + (N - 2).
- Otherwise, no such representation exists.
For example, for N = 19, we check 19 - 2 = 17. Since both 19 and 17 are prime, the answer is Yes because 19 = 2 + 17.
#include <iostream>
#include <cmath>
using namespace std;
// Checks whether a number is prime
bool isPrime(int n)
{
if (n <= 1)
return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
// Checks whether N can be expressed as
// the sum of two prime numbers
bool isPossible(int N)
{
return isPrime(N) && isPrime(N - 2);
}
int main()
{
int N = 13;
if (isPossible(N))
cout << "Yes";
else
cout << "No";
return 0;
}
Output
Yes
Explanation: For N = 13:
- 13 is prime.
- 13 - 2 = 11.
- 11 is also prime.
- Therefore, 13 = 2 + 11, so the answer is Yes.