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.

```
public class CheckPrime {
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;
}
}
```

When you run the program, the output will be:

34 = 3 + 31 34 = 5 + 29 34 = 11 + 23 34 = 17 + 17

It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:

**Disabling AdBlock on Programiz. We do not use intrusive ads.**

or

Donate on Paypal
By using Programiz, you agree to use cookies as stated in our Privacy policy Continue