Check Whether a Number can be Expressed as Sum of Two Prime Numbers in Java

Exercise:

Write a Java Program to check whether a number can be expressed as sum of two prime numbers.

Click Here to View the Solution!
public class PrimeSum{
  
   public static void main(String[] args) {
     int number = 44;
     boolean flag = false;
     for (int i = 2; i <= number / 2; ++i) {
  
       // condition to check if i is a prime number
       if (checkPrime(i)) {
  
         // condition to check if n-i is a prime number
         if (checkPrime(number - i)) {
  
           // n = primeNumber1 + primeNumber2
           System.out.printf("%d = %d + %d\n", number, i, number - i);
           flag = true;
         }
       }
     }
  
     if (!flag)
       System.out.println(number + " cannot be expressed as the sum of two prime numbers.");
   }
  
   // Function to check if the number is  prime number
   static boolean checkPrime(int num) {
     boolean isPrime = true;
  
     for (int i = 2; i <= num / 2; ++i) {
       if (num % i == 0) {
         isPrime = false;
         break;
       }
     }
  
     return isPrime;
   }
} 
Click Here to View the Output!
44 = 3 + 41
44 = 7 + 37
44 = 13 + 31
Click Here to View the Explanation!
  • This program is used to find out that whether a number can be represented in the form of a sum of two prime numbers or not by using for loops and break statements in Java.
  • A user-defined method checkPrime() is used to check whether a number is a prime number or not. If it is, the method will return true. Else, false.
  • Initially, an integer variable number is initialized as number = 44. The program now needs to find out that whether 44 can be represented as a sum of two prime numbers.
  • For this purpose, the program firstly executes a for loop with a condition starting from i = 2 till i <= number/2.
  • This for loop holds two if statements. The first if statement will check if the incoming value of ‘i’ is a prime number or not. It will return true if it is a prime number.
  • Whereas, the second if statement will check if the value of ‘number – i’ is a prime number. The reason behind using ‘number – i’ is that, on adding both i and number – i, the result will be number.
  • If the second if statement will also be true, then it can be said that number 44 is a sum of two prime numbers