#include <iostream>
using namespace std;
bool check_prime(int n);
int main() {
int n, i;
bool flag = false;
cout << "Enter a positive integer: ";
cin >> n;
for(i = 2; i <= n/2; ++i) {
if (check_prime(i)) {
if (check_prime(n - i)) {
cout << n << " = " << i << " + " << n-i << endl;
flag = true;
}
}
}
if (!flag)
cout << n << " can't be expressed as sum of two prime numbers.";
return 0;
}
// check prime number
bool check_prime(int n) {
int i;
bool is_prime = true;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
is_prime = false;
}
for(i = 2; i <= n/2; ++i) {
if(n % i == 0) {
is_prime = false;
break;
}
}
return is_prime;
}
Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
check_prime()
function to check whether a number is prime or not.main()
, we take a number from the user and store it in the variable n
.i = 2
to i = n/2
. In each iteration, we check whether i
is a prime number or not. i
is a prime, we check whether n - i
is prime or not.n
can be expressed as the sum of two prime numbers i
and n - i
.flag
to true
. Otherwise, flag
remains false
.flag
is still false
, then we know that n
can't be expressed as the sum of two primes, and we print that message on the screen.