We are uploading our contents, please refresh app.
Java Premium

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

In this program, you'll learn to check whether a given number can be expressed as a sum of two prime numbers or not. This is done with the help of loops and break statements in Java.
To accomplish this task, checkPrime() function is created.

The checkPrime() returns 1 if the number passed to the function is a prime number.
Example: Integer as a Sum of Two Prime Numbers

Programming code:
import java.util.*;
public class CheckPrime 
{
public static void main(String[] args)
{
        int number;
        boolean flag = false;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any number:");
        number=sc.nextInt();
        for (int i = 2; i <= number / 2; ++i)
        {
        // condition for i to be a prime number
            if (checkPrime(i))
            {
             // condition for n-i to be 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 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;
    }
}
When you run the program, the output will be:
Enter any number:
48
48 = 5 + 43
48 = 7 + 41
48 = 11 + 37
48 = 17 + 31
48 = 19 + 29

Online user

Download our android app Download App Submit your query
x

Get Updates On

Java & Premium Programs

Java Solved & Questions

Java Coding easy to use

Proper Coding

Straight Into Your INBOX!

We are going to send you our resources for free. To collect your copy at first, join our mailing list. We are promising not to bother you by sending useless information. So don't miss any updates, stay connected!