Java Program to Split a Number into Two Prime Number

In this java program, we will learn about how to check whether a number can be expressed as sum of two prime numbers. We will also learn to check whether a number is prime number or not.

First of all, we have to understand fundamentals of prime numbers.

  • A Prime number is a positive number greater than 1 that is only divisible by either 1 or itself.
  • Any non-prime number can be expressed as a factor of prime numbers.

How to check whether a number is prime number or not ?

Let N be the number for primality testing. Here, we will use brute force approach by testing whether N is a multiple of any integer between 2 and N/2. This is the most basic method of checking the primality of a given integer N and is called trial division method. Here is a java method to test prime numbers. It returns true of given number is prime number otherwise false.

   static boolean IsPrime(int num) {
      boolean isPrimeNumber = true;
      for (int i = 2; i <= num / 2; ++i) {
         if (num % i == 0) {
            isPrimeNumber = false;
            break;
          }
      }
      return isPrimeNumber;
   }

To understand this java program, you should have understanding of the following Java programming concepts:


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

public class PrimeSum {
  public static void main(String[] args) {
    int N;
    boolean isPrimeSum = false;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a number");
    N = scanner.nextInt();

    for (int i = 2; i <= N / 2; i++) {
      // Check if i is prime number
      if(IsPrime(i)) {
        // Check if N-i is prime number also
        if(IsPrime(N-i)) {
          System.out.format("%d = %d + %d\n", N,i,N-i);
          isPrimeSum = true;
        }
      }
    }

    if (!isPrimeSum) {
      System.out.format("%d cannot be expressed as 
        sum of two prime numbers.");
    }
  }
  // Returns true if num is prime otherwise false.
  static boolean IsPrime(int num) {
    boolean isPrimeNumber = true;
    for (int i = 2; i <= num / 2; ++i) {
      if (num % i == 0) {
        isPrimeNumber = false;
        break;
      }
    }
    return isPrimeNumber;
  }
}
Output
Enter a number
24
24 = 5 + 19
24 = 7 + 17
24 = 11 + 13
  • In above java program, we created a method called "IsPrime" to check whether a given number is prime number or not. This method returns true if number is prime otherwise false.
  • For a given number N, a for loop will iterate from 2 to N/2 and for every number i it check whether i is prime number of not.
  • If i is prime number then we check whether N-i is prime or not.
  • If N-i is also prime number then, N can be expressed as sum of two prime numbers i and N-i.