Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions maths/sieve_of_sundaram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
Sieve of Sundaram algorithm for finding prime numbers up to a given limit.

The Sieve of Sundaram generates prime numbers by eliminating integers
of the form i + j + 2ij.

Time Complexity: O(n log n)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please define n here (it is the limit). It would also help to say that this is slower than the Sieve of Eratosthenes (O(n log log n)). Also consider a "see also" note pointing at the existing sieve in maths/, so readers can compare.

Space Complexity: O(n)

Reference: https://en.wikipedia.org/wiki/Sieve_of_Sundaram
"""


def sieve_of_sundaram(limit: int) -> list[int]:
"""
Generate all prime numbers up to a given limit.

Args:
limit: Upper bound for finding primes (inclusive).

Returns:
List of prime numbers up to the given limit.

Raises:
ValueError: If limit is negative.

Examples:
>>> sieve_of_sundaram(20)
[2, 3, 5, 7, 11, 13, 17, 19]
>>> sieve_of_sundaram(10)
[2, 3, 5, 7]
>>> sieve_of_sundaram(2)
[2]
>>> sieve_of_sundaram(1)
[]
>>> sieve_of_sundaram(0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a few more doctests?

  • sieve_of_sundaram(3) -> [2, 3] and sieve_of_sundaram(4) -> [2, 3], to cover the smallest limits and an even limit
  • len(sieve_of_sundaram(100)) -> 25, to check a larger input
  • a cross-check against trial division for a range of limits, which would document that the sieve is correct, not only that a few outputs match

[]
>>> sieve_of_sundaram(-1)
Traceback (most recent call last):
...
ValueError: -1: Invalid input, please enter a non-negative integer.
"""
if limit < 0:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-integer input such as sieve_of_sundaram(10.5) currently fails with "can't multiply sequence by non-int of type 'float'", which isn't very helpful. Since the type hint says int, either leave it, or reject non-integers up front with a clearer TypeError and add a doctest for it.

msg = f"{limit}: Invalid input, please enter a non-negative integer."
raise ValueError(msg)

if limit < 2:
return []

upper_bound = (limit - 1) // 2

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A short comment here would help readers new to this sieve: each index k stands for the odd number 2k + 1, and k is marked when 2k + 1 is composite. That explains both the (limit - 1) // 2 bound and the 2 * value + 1 on line 63. A clearer name than upper_bound (e.g. max_index) would also help.

marked = [False] * (upper_bound + 1)

for i in range(1, upper_bound + 1):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: only values of i with 2 * i * (i + 1) <= upper_bound mark anything, so the outer loop does nothing for most of its range. The inner marking can also be a slice assignment, which matched the current output for every limit from 0 to 3000 in my check and was about 10x faster at limit 10**6:

i = 1
while 2 * i * (i + 1) <= upper_bound:
    start, step = 2 * i * (i + 1), 2 * i + 1
    marked[start::step] = [True] * len(range(start, upper_bound + 1, step))
    i += 1

Feel free to keep the explicit loop if you prefer clarity, since it reads closer to the textbook formula.

j = i
while i + j + 2 * i * j <= upper_bound:
marked[i + j + 2 * i * j] = True
j += 1

primes = [2]

for value in range(1, upper_bound + 1):
if not marked[value]:
prime = 2 * value + 1
if prime <= limit:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This condition can never be false. The largest candidate is 2 * upper_bound + 1, and upper_bound = (limit - 1) // 2, so it is at most limit. I checked every limit from 0 to 2999 and the condition was always true. You can drop it and simplify lines 61-65 to primes.extend(2 * value + 1 for value in range(1, upper_bound + 1) if not marked[value]), or keep the loop without the check.

primes.append(prime)

return primes
Loading