Skip to content

Commit 6c0b9dd

Browse files
authored
i have used sieve of Eratosthenes Update prime_numbers.py
basically let assum we have [1...6] so it is obvious that if 6 isdiv by 6 then it can't be a prime number which will result less time complexcity
1 parent 03a4251 commit 6c0b9dd

File tree

1 file changed

+8
-71
lines changed

1 file changed

+8
-71
lines changed

maths/prime_numbers.py

+8-71
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,5 @@
11
import math
22
from collections.abc import Generator
3-
4-
5-
def slow_primes(max_n: int) -> Generator[int, None, None]:
6-
"""
7-
Return a list of all primes numbers up to max.
8-
>>> list(slow_primes(0))
9-
[]
10-
>>> list(slow_primes(-1))
11-
[]
12-
>>> list(slow_primes(-10))
13-
[]
14-
>>> list(slow_primes(25))
15-
[2, 3, 5, 7, 11, 13, 17, 19, 23]
16-
>>> list(slow_primes(11))
17-
[2, 3, 5, 7, 11]
18-
>>> list(slow_primes(33))
19-
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
20-
>>> list(slow_primes(1000))[-1]
21-
997
22-
"""
23-
numbers: Generator = (i for i in range(1, (max_n + 1)))
24-
for i in (n for n in numbers if n > 1):
25-
for j in range(2, i):
26-
if (i % j) == 0:
27-
break
28-
else:
29-
yield i
30-
31-
32-
def primes(max_n: int) -> Generator[int, None, None]:
33-
"""
34-
Return a list of all primes numbers up to max.
35-
>>> list(primes(0))
36-
[]
37-
>>> list(primes(-1))
38-
[]
39-
>>> list(primes(-10))
40-
[]
41-
>>> list(primes(25))
42-
[2, 3, 5, 7, 11, 13, 17, 19, 23]
43-
>>> list(primes(11))
44-
[2, 3, 5, 7, 11]
45-
>>> list(primes(33))
46-
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
47-
>>> list(primes(1000))[-1]
48-
997
49-
"""
50-
numbers: Generator = (i for i in range(1, (max_n + 1)))
51-
for i in (n for n in numbers if n > 1):
52-
# only need to check for factors up to sqrt(i)
53-
bound = int(math.sqrt(i)) + 1
54-
for j in range(2, bound):
55-
if (i % j) == 0:
56-
break
57-
else:
58-
yield i
59-
60-
613
def fast_primes(max_n: int) -> Generator[int, None, None]:
624
"""
635
Return a list of all primes numbers up to max.
@@ -76,19 +18,14 @@ def fast_primes(max_n: int) -> Generator[int, None, None]:
7618
>>> list(fast_primes(1000))[-1]
7719
997
7820
"""
79-
numbers: Generator = (i for i in range(1, (max_n + 1), 2))
80-
# It's useless to test even numbers as they will not be prime
81-
if max_n > 2:
82-
yield 2 # Because 2 will not be tested, it's necessary to yield it now
83-
for i in (n for n in numbers if n > 1):
84-
bound = int(math.sqrt(i)) + 1
85-
for j in range(3, bound, 2):
86-
# As we removed the even numbers, we don't need them now
87-
if (i % j) == 0:
88-
break
89-
else:
90-
yield i
91-
21+
#it is useless to calculate who is already 2 multiple
22+
def countPrimes(self, max_n: int) -> int:
23+
seen, ans = [0] * max_n, 0
24+
for num in range(2, max_n):
25+
if seen[num]: continue
26+
ans += 1
27+
seen[num*num:n:num] = [1] * ((max_n - 1) // num - num + 1)
28+
return ans
9229

9330
def benchmark():
9431
"""

0 commit comments

Comments
 (0)