C++ Program to check whether a number be expressed as a sum of two prime numbers

Number be expressed as a sum of two prime numbers in C++

Program to check whether a number be expressed as a sum of two prime numbers

Prime number is a number which only have two divisors i.e. a number which can not be divided by any other number other than 1 or itself is a prime number.

There are many theories which express numbers as a sum of two primes like Goldbach’s Conjecture which states that any even number greater than 2 can be expressed as a sum of two primes.

Here we will check for all the numbers if they can be expressed as sum of two primes or not.

Algorithm:-

  1. Take number as input from user.
  2. Input is stored in an int type variable say num 
  3. A loop is started from i = 1 and will work till  i <= num/2
    1. Every value of i is checked for being a prime number.
    2. If i is a prime number then num – i is checked for being a prime.
    3. If both are prime then print the result
    4. Otherwise num cannot be expressed as a sum of two prime numbers.
sum of two prime numbers

C++ Code:-

//C++ Program

    //Number expressed as sum of two prime numbers

    #include<iostream>

    using namespace std;

    // Function to check prime number

    int Prime(int num)

    {

        int div=0;

        for(int i=1;i<=num;i++)

        {

            if(num%i==0)

                div++;                

        }

        if(div==2)

            return 1;

        return 0;

    }

    int main()

    {

        int check = 0, n;

        cout<< "Enter a positive integer: ";

        //user input

        cin>>n;

        for(int i = 1; i <= n/2;i++)

        {

                // condition for i to be a prime number

                if (Prime(i))

                {

                        // condition for n-i to be a prime number

                        if (Prime(n-i))

                        {

                            cout<<n <<" = "<< i <<" + " << n-i<< endl;

                            check = 1;

                        }

                }    

        }

        if (check == 0)

                cout<<n<<" cannot be expressed as the sum of two prime numbers.";

        return 0;

    }
Output
Enter a positive integer:15
15=2+13 
coding (3)