Java Program to Check Sum of Two Prime Numbers

Répondu en utilisant GPT-4o-mini par Java Q&A Hub

Question :

Write a java program to check if any number given as input is the sum of 2 prime numbers.

Réponse :

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();
    }
}

How the Program Works:

  1. isPrime Method: This method checks if a number is prime. It returns true if the number is prime and false otherwise.
  2. canBeExpressedAsSumOfTwoPrimes Method: This method checks if the input number can be expressed as the sum of two prime numbers. It iterates through all numbers from 2 to half of the input number, checking if both the current number and the difference (input number - current number) are prime.
  3. Main Method: This is where the program starts execution. It prompts the user for input, calls the method to check for the sum of two primes, and prints the result.

Example Usage:

  • If the user inputs 10, the output will be:
    10 = 3 + 7
    The number 10 can be expressed as the sum of two prime numbers.
    
  • If the user inputs 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.