|
| 1 | +""" |
| 2 | +Sieve of Eratosthenes implementation to find all prime numbers up to n. |
| 3 | +
|
| 4 | +The Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers |
| 5 | +up to a specified integer n. It works by iteratively marking the multiples of |
| 6 | +each prime number starting from 2. |
| 7 | +
|
| 8 | +Example: |
| 9 | + >>> sieve_of_eratosthenes(30) |
| 10 | + [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] |
| 11 | +""" |
| 12 | + |
| 13 | +from typing import List |
| 14 | + |
| 15 | + |
| 16 | +def sieve_of_eratosthenes(n: int) -> List[int]: |
| 17 | + """ |
| 18 | + Find all prime numbers up to n using the Sieve of Eratosthenes algorithm. |
| 19 | +
|
| 20 | + Args: |
| 21 | + n: The upper limit (inclusive) for finding prime numbers. |
| 22 | + Must be a positive integer greater than or equal to 2. |
| 23 | +
|
| 24 | + Returns: |
| 25 | + A list of prime numbers up to n, in ascending order. |
| 26 | +
|
| 27 | + Raises: |
| 28 | + ValueError: If n is less than 2. |
| 29 | +
|
| 30 | + Examples: |
| 31 | + >>> sieve_of_eratosthenes(10) |
| 32 | + [2, 3, 5, 7] |
| 33 | + >>> sieve_of_eratosthenes(20) |
| 34 | + [2, 3, 5, 7, 11, 13, 17, 19] |
| 35 | + """ |
| 36 | + if n < 2: |
| 37 | + raise ValueError("n must be a positive integer greater than or equal to 2") |
| 38 | + |
| 39 | + # Initialize a boolean array "is_prime[0..n]" and set all entries to True. |
| 40 | + # A value in is_prime[i] will be False if i is not a prime, True otherwise. |
| 41 | + is_prime = [True] * (n + 1) |
| 42 | + is_prime[0] = is_prime[1] = False # 0 and 1 are not prime numbers |
| 43 | + |
| 44 | + # Start with the first prime number, 2. |
| 45 | + for current in range(2, int(n ** 0.5) + 1): |
| 46 | + if is_prime[current]: |
| 47 | + # Mark all multiples of current as not prime. |
| 48 | + # Start from current^2 because smaller multiples would have |
| 49 | + # already been marked by smaller primes. |
| 50 | + for multiple in range(current * current, n + 1, current): |
| 51 | + is_prime[multiple] = False |
| 52 | + |
| 53 | + # Collect all prime numbers. |
| 54 | + primes = [i for i, prime in enumerate(is_prime) if prime] |
| 55 | + return primes |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + # Example usage |
| 60 | + print(sieve_of_eratosthenes(100)) |
0 commit comments