Algorithm
1. Input: a positive integer n
2. Initialize a boolean variable flag to false
3. For i = 2 to n/2:
a. If check_prime(i) is true and check_prime(n - i) is true:
i. Print n = i + (n - i)
ii. Set flag to true
4. If flag is false:
a. Print n can't be expressed as the sum of two prime numbers.
Function check_prime(num):
1. Input: a positive integer num
2. If num is 0 or 1:
a. Return false
3. For i = 2 to num/2:
a. If num is divisible by i:
i. Return false
4. Return true
Code Examples
#1 Code Example-Check Whether a Number can be Expressed as a Sum of Two Prime Numbers
Code -
C++ Programming
#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;
}
Copy The Code &
Try With Live Editor
Output
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
Demonstration
C++ Programing Example to Check Whether a Number can be Express as Sum of Two Prime Numbers-DevsEnv