Skip to content

Commit 90ce870

Browse files
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

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.Scanner;
2+
3+
public class PrintPrime {
4+
static boolean isPrime(int n) {
5+
if (n <= 1) return false; // 0 and 1 are not prime
6+
7+
for(int i = 2; i * i <= n; i++) {
8+
if(n % i == 0)
9+
return false;
10+
}
11+
return true;
12+
}
13+
public static void main(String[] args) {
14+
Scanner scanner = new Scanner(System.in);
15+
16+
System.out.print("Enter the starting number: ");
17+
int start = scanner.nextInt();
18+
19+
System.out.print("Enter the ending number: ");
20+
int end = scanner.nextInt();
21+
22+
System.out.println("Prime numbers between " + start + " and " + end + " are:");
23+
24+
int count = 0;
25+
for(int num = start; num <= end; num++) {
26+
if(isPrime(num)) {
27+
System.out.print(num + "\t"); // tab space between numbers
28+
count++;
29+
if(count % 10 == 0) { // print 10 numbers per line
30+
System.out.println();
31+
}
32+
}
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)