Java Online Compiler
Example: Prime Numbers in a Range in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Prime Numbers in a Range 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; // Numbers less than or equal to 1 are not prime } // Check for divisibility from 2 up to the square root of num // We only need to check up to sqrt(num) because if a number n has a divisor // greater than sqrt(n), it must also have a divisor smaller than sqrt(n). for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return false; // Found a divisor, so it's not prime } } return true; // No divisors found, so it's prime } public static void main(String[] args) { // Step 1: Create a Scanner object to read user input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user for the lower bound System.out.print("Enter the lower bound of the range: "); int lowerBound = scanner.nextInt(); // Step 3: Prompt the user for the upper bound System.out.print("Enter the upper bound of the range: "); int upperBound = scanner.nextInt(); // Step 4: Validate the input range if (lowerBound > upperBound) { System.out.println("Error: Lower bound cannot be greater than upper bound."); scanner.close(); return; } // Step 5: Print a header for the output System.out.println("Prime numbers between " + lowerBound + " and " + upperBound + " are:"); // Step 6: Iterate through the range and check for prime numbers for (int i = lowerBound; i <= upperBound; i++) { if (isPrime(i)) { System.out.print(i + " "); } } System.out.println(); // Print a newline for better formatting // Step 7: Close the scanner to release system resources scanner.close(); } }
Output
Clear
ADVERTISEMENTS