Checking if a Number Is the Sum of Two Prime Numbers In C++

Exercise:

Write a C++ program to check if a number can be expressed as a sum of any two prime numbers.

Click Here to View the Solution:
#include <iostream>
using namespace std;
bool TestPrime(int num);
int main()
{
    int num;
    bool flag = false;
    cout << "Insert a positive number: ";
    cin >> num;
    for(int x = 2; x <= num/2; ++x)
    {
        if (TestPrime(x))
        {
            if (TestPrime(num - x))
            {
                cout << num << " = " << x << " + " << num-x << endl;
                flag = true;
            }
        }
    }
    if (!flag)
    cout << num << " is not sum of two prime numbers";
    return 0;
}
// Test prime number
bool TestPrime(int t)
{
    bool Prime = true;    // 0 and 1 are not prime numbers
    if (t == 0 || t == 1)
    {
        Prime = false;
    }
    else 
    {
        for(int x = 2; x <= t/2; ++x)
        {
            if(t % x == 0)
            {
                Prime = false;
                break;
            }
        }
    }
    return Prime;
}
Click Here to View the Output:
Insert a positive number: 56
56 = 3 + 53
56 = 13 + 43
56 = 19 + 37
Click Here to View the Explanation:
  • A function TestPrime () is created for this code. It ensures if the entered number is a prime number.
  • We initialize a bool type variable as mark it false: bool flag = false. This is used to check if a number is the sum of prime numbers.
  • The code flags TestPrime false if the entered number t is 0 or 1.
  • Else, a for loop is executed from x = 2 until x <= t/2. Here t is the number entered by the user. Through every iteration, it is checked if t is a prime number.
  • In case x is a prime number, num - x is checked through TestPrime (). If yes, the value is displayed on the screen and TestPrime flag is changed to true.
  • The process continues until the termination of the loop.
  • If flag remains zero, it means that the number is not a sum of any two prime numbers.
%d bloggers like this: