Java Online Compiler
Example: SumOfTwoPrimes in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// SumOfTwoPrimes import java.util.Scanner; // Main class containing the entry point of the program public class Main { // 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; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get input from the user System.out.print("Enter a positive integer: "); int n = scanner.nextInt(); if (n <= 2) { System.out.println("Please enter an integer greater than 2."); scanner.close(); return; } // Step 2: Initialize a flag to track if a solution is found boolean found = false; // Step 3: Iterate from 2 up to n/2 for (int i = 2; i <= n / 2; i++) { // Step 4: Check if 'i' is a prime number if (isPrime(i)) { // Step 5: Calculate the remaining part int remaining = n - i; // Step 6: Check if the remaining part is also a prime number if (isPrime(remaining)) { System.out.println(n + " can be expressed as the sum of two prime numbers: " + i + " + " + remaining); found = true; break; // Found a pair, no need to check further } } } // Step 7: If no pair was found, print the appropriate message if (!found) { System.out.println(n + " cannot be expressed as the sum of two prime numbers."); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS