Prime Number Between Given Range In Java Using Scanner
Prime numbers are integers greater than 1 that are only divisible by 1 and themselves. Finding prime numbers within a specific range is a common programming problem. In this article, you will learn how to identify and print prime numbers within a user-defined range using Java's Scanner class for input.
Problem Statement
The task is to write a Java program that takes two integers as input from the user, representing the lower and upper bounds of a range. The program should then identify and display all prime numbers that fall within this specified range (inclusive).
Example
If the user enters 10 as the lower bound and 50 as the upper bound, the program should output:
Prime numbers between 10 and 50 are:
11 13 17 19 23 29 31 37 41 43 47
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java basics: Variables, data types, conditional statements (
if,else), loops (for,while). - Methods: Defining and calling methods.
-
Scannerclass: How to read user input from the console. - Prime numbers: The definition of a prime number.
Use Cases or Case Studies
- Cryptography: Prime numbers are fundamental in many cryptographic algorithms, such as RSA, for generating secure keys.
- Number theory research: Exploring properties of prime numbers is a core area of number theory.
- Educational tools: Programs that demonstrate prime number generation can be used to teach fundamental programming concepts and number theory.
- Performance benchmarking: Algorithms for finding prime numbers can be used to benchmark CPU performance.
- Game development: Some games might use prime numbers for generating unique sequences or challenges.
Solution Approaches
We will focus on a straightforward approach involving nested loops to check for primality.
Approach 1: Basic Primality Test with Nested Loops
This approach involves iterating through each number in the given range and, for each number, checking if it is prime. A number is prime if it is not divisible by any integer from 2 up to its square root.
One-line summary: Iterate through the range, and for each number, check divisibility by numbers from 2 up to its square root.
// 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();
}
}
Sample output:
Enter the lower bound of the range: 10
Enter the upper bound of the range: 50
Prime numbers between 10 and 50 are:
11 13 17 19 23 29 31 37 41 43 47
Stepwise explanation:
isPrime(int num)method:
- This helper method takes an integer
numand returnstrueif it's prime,falseotherwise. - It first handles edge cases: numbers less than or equal to 1 are not prime.
- It then loops from
i = 2up toi * i <= num. This optimization is based on the fact that ifnumhas a divisor greater than its square root, it must also have a divisor smaller than its square root. - Inside the loop, if
numis perfectly divisible byi(i.e.,num % i == 0), thennumis not prime, and the method returnsfalse. - If the loop completes without finding any divisors,
numis prime, and the method returnstrue.
mainmethod:
- A
Scannerobject is created to read input from the console. - The program prompts the user to enter the lower and upper bounds of the range.
- Input validation checks if the
lowerBoundis greater than theupperBoundand prints an error if it is. - It then iterates through each number
ifromlowerBoundtoupperBound(inclusive). - For each number
i, it calls theisPrime(i)method. - If
isPrime(i)returnstrue, the numberiis printed to the console, followed by a space. - After the loop, a newline character is printed for better output formatting.