Commit 1d9bd72
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
1 file changed
+29
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
0 commit comments