List Every Prime Not Exceeding a Limit
Math & Bit ManipulationAuto-graded · 15 test casesLast 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
limitis an integer.limitcan 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use the Sieve of Eratosthenes. Keep one flag per integer from 0 to limit, initially all marked "possibly prime" except 0 and 1. Then, for each p from 2 up to isqrt(limit), if p is still marked prime, mark p*p, p*p + p, p*p + 2p, ... as composite. Finally, collect every index that is still marked.
If limit < 2, return an empty list immediately.
Why it is correct
- No prime is removed. Only numbers of the form
k * pwithk >= p >= 2are crossed out, and all of those are composite. - Every composite is removed. Let
m <= limitbe composite and letqbe its smallest prime factor. Thenq * q <= m <= limit, soq <= isqrt(limit)and the outer loop reachesq. Since nothing smaller thanqdividesm,qitself was never crossed out, so it is processed. Becausem >= q*qandmis a multiple ofq, the inner loop starting atq*qwith stepqhitsm. - Starting at
p*pis safe: a multiplek * pwithk < phas a prime factor smaller thanp, so it was already crossed out earlier.
Complexity
- Time: O(n log log n), since the work for prime
pis aboutn / pand the sum of1/pover primes is aboutlog log n. - Space: O(n) bytes for the flags, plus the output list (about n / ln n entries). A
bytearraytakes about 10 MB for n = 10^7.
Reference solution
from math import isqrt
from typing import List
def list_primes_up_to(limit: int) -> List[int]:
if limit < 2:
return []
flags = bytearray([1]) * (limit + 1)
flags[0] = flags[1] = 0
for p in range(2, isqrt(limit) + 1):
if flags[p]:
start = p * p
count = (limit - start) // p + 1
flags[start:limit + 1:p] = bytearray(count)
return [value for value in range(2, limit + 1) if flags[value]]