Write a java program to check if any number given as input is the sum of 2 prime numbers.
Certainly! Below is a Java program that checks if a given number can be expressed as the sum of two prime numbers. The program includes a method to check for prime numbers and another method to determine if the input number can be expressed as the sum of two primes.
import java.util.Scanner;
public class SumOfTwoPrimes {
// Method to check if a number is prime
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;
}
// Method to check if the number can be expressed as the sum of two primes
public static boolean canBeExpressedAsSumOfTwoPrimes(int number) {
for (int i = 2; i <= number / 2; i++) {
if (isPrime(i) && isPrime(number - i)) {
System.out.println(number + " = " + i + " + " + (number - i));
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (canBeExpressedAsSumOfTwoPrimes(number)) {
System.out.println("The number " + number + " can be expressed as the sum of two prime numbers.");
} else {
System.out.println("The number " + number + " cannot be expressed as the sum of two prime numbers.");
}
scanner.close();
}
}
true
if the number is prime and false
otherwise.10
, the output will be:
10 = 3 + 7
The number 10 can be expressed as the sum of two prime numbers.
11
, the output will be:
The number 11 cannot be expressed as the sum of two prime numbers.
You can run this program in any Java environment. Just copy and paste the code into a .java
file, compile it, and run it.