Commit aef2d5d
committed
feat: Add PrintPrimeInBetween to list prime numbers within a user-defined range
WHAT the code does:
Defines a PrintPrimeInBetween class with:
- isPrime(int n): returns true if n is prime, false otherwise. Uses divisibility check up to √n for efficiency.
- main(): takes starting and ending numbers as input, then prints all primes between them.
WHY this matters:
Demonstrates an efficient prime-checking algorithm for educational purposes.
Improves readability by explicitly handling edge cases (0 and 1 are not prime).
Highlights the use of Scanner for interactive user input and loops for range traversal.
Provides a practical example of combining algorithms with input/output formatting.
HOW it works:
User inputs start and end values.
For each integer in the range:
- isPrime() tests divisibility from 2 up to √n.
- If no divisor is found, the number is printed as prime.
Example: Input 10 → 20 prints: 11 13 17 19.
Tips and gotchas:
Efficiency: Checking up to √n reduces unnecessary iterations compared to n/2.
Edge cases: Numbers ≤ 1 are handled correctly and skipped.
Scanner should be closed after use to release system resources.
For large ranges, consider more advanced algorithms like the Sieve of Eratosthenes.
The extra Scanner import can be removed as it is duplicated.
Use-cases:
Educational demo of prime number algorithms and user input handling in Java.
Quick utility for generating primes within a specified interval.
Foundation for extending into optimized prime-finding or number theory tools.
Short key: class-printprimeinbetween range-prime-check sqrt-optimization.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 90ce870 commit aef2d5d
1 file changed
+32
-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 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
0 commit comments