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


January 22, 2023, Learn eTutorial
1255

Here we are going to check whether an integer can be expressed as the sum of two prime numbers.

What is a prime number?

 A prime number (or prime integer, often simply called a "prime" for short) is a positive integer that has no positive integer divisors other than 1 and itself. E.g. 2, 3, 5, 7, 11.

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

Ask the user to enter a positive integer and store it in the variable n. Use a user function check_prime() to check whether a number is prime or not. Now, Initialize a Boolean-type variable flag to false initially. This variable is used to determine whether the input number can be expressed as the sum of two prime numbers. then we start a for loop from i = 2 to i = n/2. In each iteration, we have to check i is prime or not, if the i is prime then we have to know that n-i us prime or not, if that also is prime, we can say that the user-entered number can be expressed as the sum of prime numbers.

So, we display the result and change the flag to true or one. Otherwise, the flag remains false or zero until the end of loop. Finally, If the flag is false, the number can be expressed as sum of two prime numbers.

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Declare two integer type variables n, i and float type variable flag = false;

Step 4: Ask the user to enter a positive integer;

Step 5: Read the number into the variable n;

Step 6: Iterate a loop from i= 2 to i = n/2.
        Check if i is a prime number or not.
        If yes then check whether n-1 is prime or not
        If yes then n can be expressed as the sum of two prime numbers i and n-i

Step 7: set the flag to true;

Step 8: print the result on the screen

Step 9: Exit
 

C++ Source Code

                                          #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: 48
48 = 5 + 43
48 = 7 + 41
48 = 11 + 37
48 = 17 + 31
48 = 19 + 29