In this Java program, you’ll learn how to check whether a number can be expressed as the sum of two prime numbers. In this program, we used the following Java basics such as for
loop, if...else
conditions, and break
statements.
Here is the code of the program to check whether a number can be expressed as the sum of two prime numbers.
//Java Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
import java.util.Scanner;
public class JavaPrograms {
public static void main(String[] args) {
int number;
// create an object of Scanner class
Scanner sc = new Scanner(System.in);
// ask users to enter numbers
System.out.println("Enter a number: ");
number = sc.nextInt();
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.");
}else {
System.out.println(number + " is expressed as the sum of two prime numbers.");
}
sc.close();
}
// Function to check prime number
public 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;
}
}
Enter a number:
24
24 = 5 + 19
24 = 7 + 17
24 = 11 + 13
24 is expressed as the sum of two prime numbers.
In the above program, we have created the checkPrime()
method to check whether a number is prime or not. This method returns true
if the passed number is prime.
Here, we have a number 24. The program tries to check if 24 can be represented as the sum of two prime numbers or not.
for
loop from i = 2
to number / 2
.for
loop, we used two if
statements. The first statement checks if i
is a prime number or not.true
, the second if statement checks if the number - i
is a prime number or not. This is because the sum of i
and number - i
is equal to the number.true
, then we can say the number 24 is a valid sum of two prime numbers.
Comments