Skip to content
Closed
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
48 changes: 48 additions & 0 deletions maths/sieve_of_sundaram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
Sieve of Sundaram - Alternative prime number algorithm.
Discovered by S. P. Sundaram in 1934.
"""

from typing import List

Check failure on line 6 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

maths/sieve_of_sundaram.py:6:1: UP035 `typing.List` is deprecated, use `list` instead


def sieve_of_sundaram(limit: int) -> List[int]:

Check failure on line 9 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

maths/sieve_of_sundaram.py:9:38: UP006 Use `list` instead of `List` for type annotation
"""
Find all prime numbers up to limit using Sieve of Sundaram.

Check failure on line 12 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/sieve_of_sundaram.py:12:1: W293 Blank line contains whitespace
>>> sieve_of_sundaram(30)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
>>> sieve_of_sundaram(10)
[2, 3, 5, 7]
>>> sieve_of_sundaram(2)
[]
"""
if limit <= 2:
return []

Check failure on line 22 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/sieve_of_sundaram.py:22:1: W293 Blank line contains whitespace
n = (limit - 1) // 2
marked = [False] * (n + 1)

Check failure on line 25 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/sieve_of_sundaram.py:25:1: W293 Blank line contains whitespace
for i in range(1, n + 1):
j = i
while i + j + 2 * i * j <= n:
marked[i + j + 2 * i * j] = True
j += 1

Check failure on line 31 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/sieve_of_sundaram.py:31:1: W293 Blank line contains whitespace
primes = [2]
for i in range(1, n + 1):
if not marked[i]:
primes.append(2 * i + 1)

Check failure on line 36 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/sieve_of_sundaram.py:36:1: W293 Blank line contains whitespace
return primes



if __name__ == "__main__":
print("Sieve of Sundaram Demo")
print("-" * 20)

Check failure on line 44 in maths/sieve_of_sundaram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

maths/sieve_of_sundaram.py:44:1: W293 Blank line contains whitespace
for limit in [10, 30, 50]:
primes = sieve_of_sundaram(limit)
print(f"Primes up to {limit}: {primes}")
print(f"Found {len(primes)} primes")
Loading