Popular Tutorials
Start Learning JavaCertification Courses
Created with over a decade of experience and thousands of feedback.
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 understand this example, you should have the knowledge of the following Java programming topics:
Example: Represent a number 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;
}
}
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
forloop fromi = 2 to number / 2. - Inside the
forloop, we used twoifstatements. The first statement checks if i is prime or not.
If true, the secondifstatement checks ifnumber - iis 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.
Did you find this article helpful?