Print all primes till N
Pattern: Sieve
List every prime up to and including n with the sieve: walk upwards, record each number that is still uncrossed, and cross out its multiples from its square.
The problem
Return all prime numbers from 2 to n inclusive, in increasing order.
Think first
- How does this differ from Count Primes?
- Is n itself included?
- What is the answer for n = 1?
Hints
Brute force, and why it fails
Test each number by trial division: O(n √n).
The key insight
The sieve finds every prime in one pass with O(n log log n) total work.
Dry run
n = 10. Uncrossed in turn: 2, 3, 5, 7.
Step 1 of 2
The plan
composite = all false
for i in 2..n: if not composite[i]: record i; cross its multiples from i × i
Complexity
- Time
O(n log log n)- Space
O(n)
The sieve.
Edge cases
- n = 1: empty.
- n = 2: [2].
- n prime: included.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> primeTillN(int n) {
boolean[] composite = new boolean[n + 1];
List<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (composite[i]) continue;
primes.add(i); // still uncrossed: prime
for (long j = (long) i * i; j <= n; j += i) composite[(int) j] = true;
}
return primes;
}
}C++
class Solution {
public:
vector<int> primeTillN(int n) {
vector<bool> composite(n + 1, false);
vector<int> primes;
for (int i = 2; i <= n; i++) {
if (composite[i]) continue;
primes.push_back(i); // still uncrossed: prime
for (long long j = 1LL * i * i; j <= n; j += i) composite[j] = true;
}
return primes;
}
};Python
class Solution:
def primeTillN(self, n: int) -> list[int]:
composite = [False] * (n + 1)
primes = []
for i in range(2, n + 1):
if not composite[i]:
primes.append(i) # still uncrossed: prime
for j in range(i * i, n + 1, i):
composite[j] = True
return primesCommon mistakes
- Excluding n.
- Starting at 1.