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

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

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

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

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

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

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

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;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *