Write a C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers

C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn C++ programming concepts. You can learn C++ language at your own speed and time. One can learn concepts of C++ language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers
C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers

Write a  C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers

PROGRAM:C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers

/* C++ Program to Check Whether a Number can be Express as Sum of Two Prime Numbers */

#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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *