|
| 1 | +""" |
| 2 | +Sieve of Sundaram algorithm for finding prime numbers up to a given limit. |
| 3 | +
|
| 4 | +The Sieve of Sundaram generates prime numbers by eliminating integers |
| 5 | +of the form i + j + 2ij. |
| 6 | +
|
| 7 | +Time Complexity: O(n log n) |
| 8 | +Space Complexity: O(n) |
| 9 | +
|
| 10 | +Reference: https://en.wikipedia.org/wiki/Sieve_of_Sundaram |
| 11 | +""" |
| 12 | + |
| 13 | + |
| 14 | +def sieve_of_sundaram(limit: int) -> list[int]: |
| 15 | + """ |
| 16 | + Generate all prime numbers up to a given limit. |
| 17 | +
|
| 18 | + Args: |
| 19 | + limit: Upper bound for finding primes (inclusive). |
| 20 | +
|
| 21 | + Returns: |
| 22 | + List of prime numbers up to the given limit. |
| 23 | +
|
| 24 | + Raises: |
| 25 | + ValueError: If limit is negative. |
| 26 | +
|
| 27 | + Examples: |
| 28 | + >>> sieve_of_sundaram(20) |
| 29 | + [2, 3, 5, 7, 11, 13, 17, 19] |
| 30 | + >>> sieve_of_sundaram(10) |
| 31 | + [2, 3, 5, 7] |
| 32 | + >>> sieve_of_sundaram(2) |
| 33 | + [2] |
| 34 | + >>> sieve_of_sundaram(1) |
| 35 | + [] |
| 36 | + >>> sieve_of_sundaram(0) |
| 37 | + [] |
| 38 | + >>> sieve_of_sundaram(-1) |
| 39 | + Traceback (most recent call last): |
| 40 | + ... |
| 41 | + ValueError: -1: Invalid input, please enter a non-negative integer. |
| 42 | + """ |
| 43 | + if limit < 0: |
| 44 | + msg = f"{limit}: Invalid input, please enter a non-negative integer." |
| 45 | + raise ValueError(msg) |
| 46 | + |
| 47 | + if limit < 2: |
| 48 | + return [] |
| 49 | + |
| 50 | + upper_bound = (limit - 1) // 2 |
| 51 | + marked = [False] * (upper_bound + 1) |
| 52 | + |
| 53 | + for i in range(1, upper_bound + 1): |
| 54 | + j = i |
| 55 | + while i + j + 2 * i * j <= upper_bound: |
| 56 | + marked[i + j + 2 * i * j] = True |
| 57 | + j += 1 |
| 58 | + |
| 59 | + primes = [2] |
| 60 | + |
| 61 | + for value in range(1, upper_bound + 1): |
| 62 | + if not marked[value]: |
| 63 | + prime = 2 * value + 1 |
| 64 | + if prime <= limit: |
| 65 | + primes.append(prime) |
| 66 | + |
| 67 | + return primes |
0 commit comments