Algorithm


  1. Start with a given integer num that you want to check.
  2. Create a function isPrime(n) to check if a given number n is prime. This function should return true if n is prime and false otherwise.
  3. Iterate through all possible pairs of numbers (i, j) where i and j are less than num.
  4. For each pair (i, j), check if both i and j are prime numbers using the isPrime function.
  5. If both i and j are prime, check if their sum is equal to the given num.
  6. If the sum is equal to num, then num can be expressed as the sum of two prime numbers.
  7. If no such pair is found after iterating through all possible pairs, conclude that num cannot be expressed as the sum of two prime numbers.

 

Code Examples

#1 Code Example- Represent a number as Sum of Two Prime Numbers

Code - Java Programming

public class Main {

  public static void main(String[] args) {
    int number = 34;
    boolean flag = false;
    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;
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
Advertisements

Demonstration


Java Programing Example to Check Whether a Number can be Expressed as Sum of Two Prime Numbers-DevsEnv