Title description
Any even number (greater than 2) can be composed of two prime numbers. There are many situations in which two prime numbers make up an even number. This question requires the output of a prime number pair that forms a specified even number with the smallest difference between the two prime numbers.
This question contains multiple sets of sample input.
Enter description:
Enter an even number
Output description:
Output two prime numbers
Sample
input20
Output
7
13
Topic analysis
- First, we should determine whether a number is prime. The range of determining prime numbers here is from 2 to square root n. If there is a number in this interval that can be divisible by n, it means that n is not a prime number; if not, n is a prime number.
- Find suitable prime numbers from 1/2 of this even number to both sides, so that you can ensure that the difference between the two prime numbers is the smallest. If you find it, you can jump out of the loop.
Reference Code
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(int n)
{
int sq = sqrt(n);
for(int i = 2; i <= sq; ++i)
{
if(n%i == 0)
return false;
}
return true;
}
int main()
{
int num;
while(cin >> num)
{
int half = num/2;
int i = 0;
for(i = half; i > 2; ++i)
{
if(isPrime(i) && isPrime(num-i))
break;
}
cout << num-i << endl << i << endl;
}
return 0;
}