Commit 90ce870
committed
feat: Add PrintPrime program to display prime numbers in a range with formatted output
WHAT the code does:
Defines a PrintPrime class with:
- isPrime(int n): returns true if n is prime, false otherwise.
- main(): reads a start and end value from the user, prints all prime numbers between them, formatted with 10 primes per line.
WHY this matters:
Improves on a basic prime-checking program by:
- Handling edge cases explicitly (0 and 1 are not prime).
- Using sqrt(n) as the loop limit, making prime checks more efficient than n/2.
- Adding formatted output with tab spacing and line breaks for readability.
Shows a real-world refinement of a classic beginner algorithm.
HOW it works:
User inputs a start and end value.
For each number in the range:
- isPrime() tests divisibility from 2 up to √n.
- If prime, prints the number followed by a tab.
A counter tracks how many primes have been printed; every 10 primes, a newline is inserted.
Example: Input 1 → 50 prints primes neatly arranged in rows of 10.
Tips and gotchas:
Efficiency: Checking up to √n reduces time complexity of prime testing.
Readability: Tab spacing and row breaks make large outputs easier to scan.
Edge cases: Numbers ≤ 1 are skipped correctly.
Scanner should be closed after use to avoid resource warnings.
For very large ranges, consider Sieve of Eratosthenes for significant performance gains.
Use-cases:
Educational program demonstrating improved prime checking.
Useful tool for quickly listing primes in a given range with formatted output.
Foundation for learning about algorithmic optimization and user-friendly console formatting.
Short key: class-printprime range-primes formatted-output sqrt-optimization.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 1d9bd72 commit 90ce870
1 file changed
+35
-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 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
0 commit comments