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

To understand this example, you should have the knowledge of the following C++ programming topics:


This program takes a positive integer from the user and checks whether that number can be expressed as the sum of two prime numbers.

If the number can be expressed as the sum of two prime numbers, the output shows the combination of the prime numbers.

To perform this task, a user-defined function is created to check prime number.


Example: Check Whether a Number can be Expressed as a 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;
}

Output

Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

In this program, we use the check_prime() function to check whether a number is prime or not.

In main(), we take a number from the user and store it in the variable n.

We also initialize a bool variable flag to false. We use this variable to determine whether the input number can be expressed as the sum of two prime numbers.

We then iterate a loop from i = 2 to i = n/2. In each iteration, we check whether i is a prime number or not.

If i is a prime, we check whether n - i is prime or not.

If n - i is also a prime, then we know that n can be expressed as the sum of two prime numbers i and n - i.

So, we print the result on the screen and change the value of flag to true. Otherwise, flag remains false.

This process continues until the loop ends.

If 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.


Also Read:

Did you find this article helpful?