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

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Represent a number as Sum of Two Prime Numbers

Output

34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

In the above example, we have created the checkPrime() method to find whether a number is prime or not. The method returns true if the passed number is prime.

Here, we have a number 34. The program tries to check if 34 can be represented as the sum of two prime numbers.

Working of Program

  • First, we run a for loop from i = 2 to number / 2.
  • Inside the for loop, we used two if statements. The first statement checks if i is prime or not.

    If true, the second if statement checks if number - i is prime or not. This is because the sum of i and number - i is equal to number.
  • If the second statement is also true, then we can say the number 34 is a valid sum of two prime numbers.