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
38 changes: 17 additions & 21 deletions maths/sieve_of_eratosthenes.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Sieve of Eratosthones
Sieve of Eratosthenes

The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or
equal to a given value.
Expand All @@ -9,11 +9,11 @@

doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
optimized by : Sumit Nayak (https://github.com/Sumit210106/)
"""

from __future__ import annotations

import math

Check failure on line 16 in maths/sieve_of_eratosthenes.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

maths/sieve_of_eratosthenes.py:15:1: I001 Import block is un-sorted or un-formatted


def prime_sieve(num: int) -> list[int]:
Expand All @@ -38,26 +38,22 @@
msg = f"{num}: Invalid input, please enter a positive integer."
raise ValueError(msg)

sieve = [True] * (num + 1)
prime = []
start = 2
end = int(math.sqrt(num))

while start <= end:
# If start is a prime
if sieve[start] is True:
prime.append(start)
if num < 2:
return []

# Set multiples of start be False
for i in range(start * start, num + 1, start):
if sieve[i] is True:
sieve[i] = False

start += 1

for j in range(end + 1, num + 1):
if sieve[j] is True:
prime.append(j)
sieve = [True] * (num + 1)
prime = [2]

# marked all even numbers as non-prime
for i in range(3, int(math.sqrt(num)) + 1, 2):
if sieve[i]:
for j in range(i * i, num + 1, 2 * i):
sieve[j] = False

# collect odd primes
for k in range(3, num + 1, 2):
if sieve[k]:
prime.append(k)

return prime

Expand Down
Loading