Java Number Program · OT25
Print Prime Numbers in a Range in Java
Instead of testing each number, cross out the multiples of every prime. Whatever is never crossed out is prime.
Problem Statement
Given an integer n, return every prime number from 2 to n in increasing order.
A prime has exactly two divisors, 1 and itself, so 0 and 1 are not prime. For n < 2 the list is empty.
Input/Output Examples
n = 30Output[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]Explanation: ten primes.n = 2Output[2]Explanation: 2 is the only even prime.n = 1Output[]Explanation: 1 is not prime.Visual Explanation
Crossing out starts at p × p, because smaller multiples of p were already removed by smaller primes. The outer loop can stop once p × p > n.
Approaches
The sieve shares work between numbers. Trial division tests each number on its own.
Approach 1: Sieve of Eratosthenes (Recommended)
Idea: mark multiples of each prime as composite in a boolean[]; the unmarked numbers are prime.
- Create
composite[0..n]. - For each
pwithp × p ≤ nthat is not marked, markp², p² + p, …. - Collect every unmarked number from 2 to
n.
Time: O(n log log n) · Space: O(n).
Approach 2: Trial Division
Idea: for each number, try dividing by every value from 2 to its square root.
- For each
xfrom 2 ton, test divisorsdwithd × d ≤ x. - If none divides
x, it is prime.
Time: O(n √n) · Space: O(1). Excluding the output.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Sieve of Eratosthenes (Recommended)
The (long) p * p comparison avoids overflow when n is close to Integer.MAX_VALUE.
import java.util.ArrayList;
import java.util.List;
public class PrimesSieve {
// Cross out multiples of each prime, starting from its square
static List<Integer> primesUpTo(int n) {
List<Integer> primes = new ArrayList<>();
if (n < 2) {
return primes;
}
boolean[] composite = new boolean[n + 1];
for (int p = 2; (long) p * p <= n; p++) {
if (!composite[p]) {
for (int m = p * p; m <= n; m += p) {
composite[m] = true;
}
}
}
for (int i = 2; i <= n; i++) {
if (!composite[i]) {
primes.add(i);
}
}
return primes;
}
public static void main(String[] args) {
int[] inputs = {30, 2, 1};
for (int n : inputs) {
System.out.println("n=" + n + " -> " + primesUpTo(n));
}
}
}
n=30 -> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] n=2 -> [2] n=1 -> []
Time complexity: O(n log log n) · Space complexity: O(n).
Approach 2: Trial Division
Fine for checking one number, but slower than the sieve for a whole range.
import java.util.ArrayList;
import java.util.List;
public class PrimesTrialDivision {
// Tests each number separately by dividing by 2..sqrt(number)
static List<Integer> primesUpTo(int n) {
List<Integer> primes = new ArrayList<>();
for (int x = 2; x <= n; x++) {
boolean prime = true;
for (int d = 2; (long) d * d <= x; d++) {
if (x % d == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(x);
}
}
return primes;
}
public static void main(String[] args) {
int[] inputs = {30, 2, 1};
for (int n : inputs) {
System.out.println("n=" + n + " -> " + primesUpTo(n));
}
}
}
n=30 -> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] n=2 -> [2] n=1 -> []
Time complexity: O(n √n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Sieve of Eratosthenes | O(n log log n) | O(n) |
| Trial Division | O(n √n) | O(1) |
Here n is the upper limit. The sieve does about n log log n crossings; trial division can take up to √x divisions for every x.
Interview Tips and Recommended Approach
- Start crossing at
p × p. Smaller multiples are already crossed. - Stop the outer loop at
√n. Larger primes have no new multiples to mark. - Know the memory cost. The sieve needs one boolean per number; a segmented sieve handles huge ranges.
- Explain why 1 is not prime if asked; it has only one divisor.
Recommended Approach: Sieve of Eratosthenes
Why: it finds all primes in a range far faster than testing each number, with a few lines of code.