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

To understand this example, you should have knowledge of following C++ programming topics:
Examples C++ Objects and Class, C++ Constructors Tutorials, Coding C++ Objects & Function, Program C++ Operator Overloading
This program takes a positive integer from user and checks whether that number can be expressed as the sum of two prime numbers. If that number can be expressed as sum of two prime numbers then, that number is expressed as sum of two prime numbers in output. To perform this task, a user-defined function is created to check prime number
Tag : Examples C++ Objects and Class, C++ Constructors Tutorials, Coding C++ Objects & Function, Program C++ Operator Overloading

#include <iostream>
using namespace std;
int check_prime(int n);
int main()
{
    int n, i, flag=0;
    cout << "Enter a positive  integer: ";
    cin >> n;
    for(i=2; i<=n/2; ++i)
    {
        if (check_prime(i)==0)
        {
            if ( check_prime(n-i)==0)
            {
                cout << n << " = " << i << " + " << n-i << endl;
                flag=1;
            }

        }
    }
    if (flag==0)
      cout << n << " can't be expressed as sum of two prime numbers.";
    return 0;
}
int check_prime(int n) /*check prime number*/
{
  int i, flag=0;
  for(i=2;i<=n/2;++i)
  {
      if(n%i==0)
      {
          flag=1;
          break;
      }
  }
  return flag;
}

Output

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

Silahkan komentar pada kolom dibawah ini jika ada yang ingin ditanyakan tentang C++ program to Check Whether a Number can be Express as Sum of Two Prime Numbers.

0 Response to "C++ program to Check Whether a Number can be Express as Sum of Two Prime Numbers"