Skip to content

Commit 1d9bd72

Browse files
committed
feat: Add PrimeNumbers program to print primes within a user-specified range
WHAT the code does: Defines a PrimeNumbers class with: - isPrime(int n): checks whether a number is prime by testing divisibility from 2 to n/2. - main(): reads a start and end value from user input, iterates through the range, and prints prime numbers. WHY this matters: Provides a simple yet practical implementation of prime checking. Demonstrates Scanner for interactive input and loops for range iteration. Highlights algorithmic thinking: checking factors to classify numbers as prime or composite. Useful as an educational program combining control flow, functions, and user interaction. HOW it works: User provides a starting and ending integer. For each number in the range: - isPrime(num) tests divisibility from 2 up to n/2. - If no divisor is found, the number is printed as prime. Example: input start=10, end=20 → output primes: 11 13 17 19. Tips and gotchas: The loop condition in isPrime should ideally be i <= sqrt(n) instead of n/2 for efficiency. Current implementation treats numbers < 2 as prime (e.g., 0, 1) because no divisor is found; explicit checks are needed. For larger ranges, this algorithm is inefficient compared to sieve-based approaches. Always close the Scanner after use to release system resources. Use-cases: Educational demonstration of prime number algorithms and input handling. Basic number theory exploration for beginners in Java. Foundation for extending into optimized algorithms like Sieve of Eratosthenes. Short key: class-primenumbers range-prime-check scanner-input. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 9954233 commit 1d9bd72

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.Scanner;
2+
3+
public class PrimeNumbers {
4+
static boolean isPrime(int n) {
5+
for(int i = 2; i < n/2; i++) { // check divisibility
6+
if(n % i == 0) // n has a factor other than 1 and itself → not prime
7+
return false;
8+
}
9+
return true;
10+
}
11+
public static void main(String[] args) {
12+
Scanner scanner = new Scanner(System.in);
13+
14+
System.out.print("Enter the starting number: ");
15+
int start = scanner.nextInt();
16+
17+
System.out.print("Enter the ending number: ");
18+
int end = scanner.nextInt();
19+
20+
System.out.println("Prime numbers between " + start + " and " + end + " are:");
21+
22+
// Loop through the range and print primes.
23+
for(int num = start; num <= end; num++) {
24+
if(isPrime(num)) {
25+
System.out.print(num + " ");
26+
}
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)