Skip to content

Commit 40608c9

Browse files
committed
Update optimised_sieve_of_eratosthenes.py
1 parent eb55817 commit 40608c9

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed
Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
1-
# Optimized Sieve of Eratosthenes: An efficient algorithm to compute all prime numbers up to n.
1+
# Optimized Sieve of Eratosthenes: An efficient algorithm to compute all prime numbers up to limit.
22
# This version skips even numbers after 2, improving both memory and time usage.
3-
# It is particularly efficient for larger n (e.g., up to 10**8 on typical hardware).
3+
# It is particularly efficient for larger limits (e.g., up to 10**8 on typical hardware).
44
# Wikipedia URL - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
55

66
from math import isqrt
77

8-
def optimized_sieve(n: int) -> list[int]:
8+
def optimized_sieve(limit: int) -> list[int]:
99
"""
10-
Compute all prime numbers up to and including n using an optimized Sieve of Eratosthenes.
10+
Compute all prime numbers up to and including `limit` using an optimized Sieve of Eratosthenes.
1111
1212
This implementation skips even numbers after 2 to reduce memory and runtime by about 50%.
1313
1414
Parameters
1515
----------
16-
n : int
16+
limit : int
1717
Upper bound (inclusive) of the range in which to find prime numbers.
18-
Expected to be a non-negative integer. If n < 2 the function returns an empty list.
18+
Expected to be a non-negative integer. If limit < 2 the function returns an empty list.
1919
2020
Returns
2121
-------
2222
list[int]
23-
A list of primes in ascending order that are <= n.
23+
A list of primes in ascending order that are <= limit.
2424
2525
Examples
2626
--------
@@ -33,18 +33,18 @@ def optimized_sieve(n: int) -> list[int]:
3333
>>> optimized_sieve(30)
3434
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
3535
"""
36-
if n < 2:
36+
if limit < 2:
3737
return []
3838

3939
# Handle 2 separately, then consider only odd numbers
40-
primes = [2] if n >= 2 else []
40+
primes = [2] if limit >= 2 else []
4141

42-
# Only odd numbers from 3 to n
43-
size = (n - 1) // 2
42+
# Only odd numbers from 3 to limit
43+
size = (limit - 1) // 2
4444
is_prime = [True] * (size + 1)
45-
limit = isqrt(n)
45+
bound = isqrt(limit)
4646

47-
for i in range((limit - 1) // 2 + 1):
47+
for i in range((bound - 1) // 2 + 1):
4848
if is_prime[i]:
4949
p = 2 * i + 3
5050
# Start marking from p^2, converted to index
@@ -57,5 +57,4 @@ def optimized_sieve(n: int) -> list[int]:
5757

5858

5959
if __name__ == "__main__":
60-
6160
print(optimized_sieve(50))

0 commit comments

Comments
 (0)