Skip to content

Commit be17417

Browse files
authored
Update prime_sieve_eratosthenes.py
1 parent 03a4251 commit be17417

File tree

1 file changed

+48
-34
lines changed

1 file changed

+48
-34
lines changed

maths/prime_sieve_eratosthenes.py

+48-34
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,63 @@
11
"""
2-
Sieve of Eratosthenes
2+
# Sieve of Eratosthenes
33
4-
Input: n = 10
5-
Output: 2 3 5 7
4+
# Input: n = 10
5+
# Output: 2 3 5 7
66
7-
Input: n = 20
8-
Output: 2 3 5 7 11 13 17 19
7+
# Input: n = 20
8+
# Output: 2 3 5 7 11 13 17 19
99
10-
you can read in detail about this at
11-
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
12-
"""
10+
# you can read in detail about this at
11+
# https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
12+
# """
13+
14+
15+
# def prime_sieve_eratosthenes(num: int) -> list[int]:
16+
# """
17+
# Print the prime numbers up to n
1318

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+
# """
1432

15-
def prime_sieve_eratosthenes(num: int) -> list[int]:
16-
"""
17-
Print the prime numbers up to n
33+
# if num <= 0:
34+
# raise ValueError("Input must be a positive integer")
1835

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-
"""
36+
# primes = [True] * (num + 1)
3237

33-
if num <= 0:
34-
raise ValueError("Input must be a positive integer")
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
3544

36-
primes = [True] * (num + 1)
45+
# return [prime for prime in range(2, num + 1) if primes[prime]]
3746

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
47+
def sieve(n):
48+
isprime[0] = isprime[1] = False
49+
for i in range(2, math.sqrt(n) + 1):
50+
if isprime[i]:
51+
primes.append(i)
52+
for j in range(i*i, n+1, i):
53+
isprime[j] = False
4454

45-
return [prime for prime in range(2, num + 1) if primes[prime]]
55+
n = int(input())
56+
isprime = [True for i in range(n+1)]
57+
primes = []
4658

59+
print('The prime numbers from 1 to', n, 'are:')
60+
print(*primes)
4761

4862
if __name__ == "__main__":
4963
import doctest

0 commit comments

Comments
 (0)