Smallest Primes Prefix: Build the First n Primes
Math & Bit ManipulationAuto-graded · 16 test casesLast updated
Generate the first n primes in ascending order, which tests sieve design with an upper bound derived from a count, plus handling of non-positive n.
Smallest Primes Prefix
Write a function that takes a count n and returns the n smallest prime numbers as a list in ascending order.
A prime is an integer greater than 1 whose only positive divisors are 1 and itself. The sequence starts 2, 3, 5, 7, 11, 13, and so on.
Rules
- The result must contain exactly
nprimes, sorted from smallest to largest, with no gaps (it is the prefix of the sequence of all primes). - If
nis zero or negative, return an empty list. - The function receives only
n. No upper limit on the primes is given, so your solution must decide how far to search.
Constraints
nis an integer; it may be zero or negative.- For positive
n, the answer should be computed efficiently enough to handle values ofnin the hundreds of thousands or more within a reasonable time. - The return value is a list of integers.
Examples
Example 1
Input: smallest_n_primes(0)
Output: []
Example 2
Input: smallest_n_primes(1)
Output: [2]
Example 3
Input: smallest_n_primes(5)
Output: [2, 3, 5, 7, 11]
Example 4
Input: smallest_n_primes(10)
Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Hints
Hint 1
You are given a count, not a limit. Think about how to get a safe upper bound for the n-th prime, or how to avoid needing one.
Hint 2
A Sieve of Eratosthenes marks multiples of each prime starting at p*p. For n >= 6, the n-th prime is below n * (ln n + ln ln n); handle small n separately with a fixed limit.
Hint 3
As a safety net, if the sieve yields fewer than n primes, double the limit and repeat. Don't forget n <= 0 and that 2 is prime.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A sieve needs an upper limit, but the input is only a count. The key step is choosing a limit that is guaranteed to contain at least n primes.
- If
n <= 0, return[]. - Pick a limit:
- For
n < 6, use a small fixed limit (15 contains the first five primes 2, 3, 5, 7, 11, 13). - For
n >= 6, the n-th prime is less thann * (ln n + ln ln n)(Rosser's bound), so use that value plus a small margin.
- For
- Run the Sieve of Eratosthenes up to the limit: for each
pwithp * p <= limitthat is still marked prime, mark every multiple ofpfromp * pupward as composite. - Collect the surviving indices and return the first
n. - If fewer than
nprimes were found (for example, due to floating-point rounding), double the limit and repeat, so correctness never depends on the bound alone.
Why it is correct
Every composite m <= limit has a prime factor p <= sqrt(m) <= sqrt(limit). When the loop reaches p, it marks m as a multiple of p. Starting at p * p is safe because smaller multiples k * p with k < p have a smaller prime factor and were already marked. Indices 0 and 1 are explicitly cleared. Since the limit contains at least n primes (or is doubled until it does), the first n survivors in order are exactly the n smallest primes.
Complexity
With limit N ≈ n ln n:
- Time:
O(N log log N). - Space:
O(N)for the flag array, plusO(n)for the output.
Reference solution
from math import log
from typing import List
def smallest_n_primes(n: int) -> List[int]:
if n <= 0:
return []
if n < 6:
limit = 15
else:
limit = int(n * (log(n) + log(log(n)))) + 10
while True:
flags = bytearray([1]) * (limit + 1)
flags[0] = 0
flags[1] = 0
p = 2
while p * p <= limit:
if flags[p]:
for multiple in range(p * p, limit + 1, p):
flags[multiple] = 0
p += 1
primes = [value for value, flag in enumerate(flags) if flag]
if len(primes) >= n:
return primes[:n]
limit *= 2