KatInterview

List Every Prime Not Exceeding a Limit

Math & Bit ManipulationAuto-graded · 15 test cases
MediumAuto-gradedMath & Bit Manipulationsieveprimesnumber-theory

Last updated

Tests whether you can enumerate all primes up to a limit efficiently using a sieve instead of per-number primality tests, including the n below 2 edge case.

List Every Prime Not Exceeding a Limit

Given an integer limit, return a list of all prime numbers that are less than or equal to limit, sorted in ascending order.

A prime is an integer greater than 1 whose only positive divisors are 1 and itself. In particular, the number 1 is not prime, so it must never appear in the result.

If limit is smaller than 2, there are no primes to report and the result is an empty list.

The solution must stay fast and memory-friendly for values of limit as large as 10^7, so testing every number individually by trial division is too slow.

Constraints

  • limit is an integer.
  • limit can be 0, 1, or negative; return [] in those cases.
  • limit <= 10^7.
  • The returned list must be in strictly ascending order with no duplicates.

Examples

Example 1

Input: list_primes_up_to(10)

Output: [2, 3, 5, 7]

Example 2

Input: list_primes_up_to(1)

Output: []

Example 3

Input: list_primes_up_to(30)

Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Hints

Hint 1

Instead of asking whether each number is prime, think about crossing out the numbers that are definitely composite.

Hint 2

When you process a prime p, you can begin crossing out at p*p, because smaller multiples of p have a smaller prime factor and were already removed. This also means the outer loop only needs to go up to the integer square root of limit.

Hint 3

Use a bytearray of flags rather than a list of Python objects, and use slice assignment to clear all multiples of p in one operation. Don't forget that 0 and 1 are not prime.