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



You are given a number and you need to write a C++ program to check whether a number can be expressed as sum of two prime numbers.

Input / Output Scenarios

Following is the input-output statement:

Input: n = 19
Output: 19 can be expressed as the sum of two prime numbers.
Explanation: 19 = 17 + 2, and both 17 and 2 are prime numbers.

Input: n = 36
Output: 36 can be expressed as the sum of two prime numbers.
Explanation: 36 = 31 + 5, and both 31 and 5 are prime numbers.

C++ Program to Check if a Number is Sum of Two Primes

Below the program checks whether a given number can be expressed as the sum of two prime numbers. It then print all such prime pairs that add up to input number.

#include<iostream>
using namespace std;

// function to check whether a number is prime
int func(int num) {
   int i;
   int flag = 1;
   for(i = 2; i <= num/2; ++i) {
      if(num % i == 0) {
	     // Not prime if divisible by any number other than 1 and itself
         flag = 0;
         break;
      }
   }
   
   // returns 1 if prime, 0 if not
   return flag;
}
int main() {
   int num , i;
   cout << "Enter a number : \n";
   cin >> num;
   
   // loop through all numbers from 2 to num/2
   for(i = 2; i <= num/2; ++i) {
   
      // check if i is a prime number
      if (func(i)) {
	  
	     // check if (num - i) is also a prime number
         if (func(num - i)) {
		    // If both are prime, print the expression
            cout << num << " = " << i << " + " << num-i << endl;
         }
      }
   }
   return 0;
}

The above code produces the following result:

Enter a number : 18
18 = 5 + 13
18 = 7 + 11
Updated on: 2025-06-09T11:28:29+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements