Skip to content

maths: add Sieve of Sundaram - #15508

Open
peeyushtiwary27 wants to merge 1 commit into
TheAlgorithms:masterfrom
peeyushtiwary27:fix-invalid-return-type
Open

peeyushtiwary27 wants to merge 1 commit into
TheAlgorithms:masterfrom
peeyushtiwary27:fix-invalid-return-type

Conversation

@peeyushtiwary27

Copy link
Copy Markdown
Contributor

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues, then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Oct 5, 2026

@jgohel9902 jgohel9902 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the contribution. The implementation is correct: I compared it to trial division for limits up to 3000 and found no differences. A few small suggestions inline: a redundant condition, one clarifying comment, extra doctests and clearer complexity wording.

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.

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.

upper_bound = (limit - 1) // 2
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.

[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

...
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.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants