Skip to content

Added odd_sieve.py #8740

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 17, 2023
Merged
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
42 changes: 42 additions & 0 deletions maths/odd_sieve.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from itertools import compress, repeat
from math import ceil, sqrt


def odd_sieve(num: int) -> list[int]:
"""
Returns the prime numbers < `num`. The prime numbers are calculated using an
odd sieve implementation of the Sieve of Eratosthenes algorithm
(see for reference https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes).

>>> odd_sieve(2)
[]
>>> odd_sieve(3)
[2]
>>> odd_sieve(10)
[2, 3, 5, 7]
>>> odd_sieve(20)
[2, 3, 5, 7, 11, 13, 17, 19]
"""

if num <= 2:
return []
if num == 3:
return [2]

# Odd sieve for numbers in range [3, num - 1]
sieve = bytearray(b"\x01") * ((num >> 1) - 1)

for i in range(3, int(sqrt(num)) + 1, 2):
if sieve[(i >> 1) - 1]:
i_squared = i**2
sieve[(i_squared >> 1) - 1 :: i] = repeat(
0, ceil((num - i_squared) / (i << 1))
)

return [2] + list(compress(range(3, num, 2), sieve))


if __name__ == "__main__":
import doctest

doctest.testmod()