KatInterview

Smallest Primes Prefix: Build the First n Primes

Math & Bit ManipulationAuto-graded · 16 test cases
MediumAuto-gradedMath & Bit Manipulationprimessievenumber-theory

Last 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 n primes, sorted from smallest to largest, with no gaps (it is the prefix of the sequence of all primes).
  • If n is 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

  • n is an integer; it may be zero or negative.
  • For positive n, the answer should be computed efficiently enough to handle values of n in 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.