MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / prime_sieve_eratosthenes

Function prime_sieve_eratosthenes

maths/prime_sieve_eratosthenes.py:15–45  ·  view source on GitHub ↗

Print the prime numbers up to n >>> prime_sieve_eratosthenes(10) [2, 3, 5, 7] >>> prime_sieve_eratosthenes(20) [2, 3, 5, 7, 11, 13, 17, 19] >>> prime_sieve_eratosthenes(2) [2] >>> prime_sieve_eratosthenes(1) [] >>> prime_sieve_eratosthenes(-1) Traceback

(num: int)

Source from the content-addressed store, hash-verified

13
14
15def prime_sieve_eratosthenes(num: int) -> list[int]:
16 """
17 Print the prime numbers up to n
18
19 >>> prime_sieve_eratosthenes(10)
20 [2, 3, 5, 7]
21 >>> prime_sieve_eratosthenes(20)
22 [2, 3, 5, 7, 11, 13, 17, 19]
23 >>> prime_sieve_eratosthenes(2)
24 [2]
25 >>> prime_sieve_eratosthenes(1)
26 []
27 >>> prime_sieve_eratosthenes(-1)
28 Traceback (most recent call last):
29 ...
30 ValueError: Input must be a positive integer
31 """
32
33 if num <= 0:
34 raise ValueError("Input must be a positive integer")
35
36 primes = [True] * (num + 1)
37
38 p = 2
39 while p * p <= num:
40 if primes[p]:
41 for i in range(p * p, num + 1, p):
42 primes[i] = False
43 p += 1
44
45 return [prime for prime in range(2, num + 1) if primes[prime]]
46
47
48if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected