Java program to check whether a number can be expressed as sum of two prime numbers
Sure, here's a Java program to check whether a number can be expressed as the sum of two prime numbers:
public class SumOfTwoPrimes { public static void main(String[] args) { int n = 20; boolean found = false; for (int i = 2; i <= n/2; i++) { if (isPrime(i)) { if (isPrime(n - i)) { System.out.println(n + " can be expressed as the sum of " + i + " and " + (n-i)); found = true; } } } if (!found) { System.out.println(n + " cannot be expressed as the sum of two prime numbers"); } } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } }
In this program, we first define an integer n
to represent the number to check. We also define a boolean variable found
to keep track of whether we have found a pair of prime numbers that add up to n
.
We use a for
loop to iterate from 2 to n/2
, which is the largest possible value of one of the prime numbers in the sum. For each value of i
, we check whether i
is prime by calling the isPrime
method.
If i
is prime, we check whether n - i
is also prime. If it is, we print out a message indicating that n
can be expressed as the sum of i
and n - i
, and set found
to true.
If we reach the end of the loop without finding a pair of prime numbers that add up to n
, we print out a message indicating that n
cannot be expressed as the sum of two prime numbers.
The isPrime
method is a helper method that takes an integer num
as input and returns a boolean indicating whether num
is prime. We first check whether num
is less than or equal to 1, as 1 is not considered a prime number. We then use a for
loop to check whether num
is divisible by any integer from 2 to the square root of num
. If num
is divisible by any of these integers, we return false. Otherwise, we return true.