Skip to content

Commit 46bc673

Browse files
obelisk0114cclauss
authored andcommitted
Add doctest to maths/sieve_of_eratosthenes.py and remove other/finding_primes.py (#1078)
Both of the two files implemented sieve of eratosthenes. However, there was a bug in other/finding_primes.py, and the time complexity was larger than the other. Therefore, remove other/finding_primes.py and add doctest tomaths/sieve_of_eratosthenes.py.
1 parent c27bd51 commit 46bc673

File tree

2 files changed

+36
-23
lines changed

2 files changed

+36
-23
lines changed

maths/sieve_of_eratosthenes.py

+36-2
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,53 @@
1-
"""Sieve of Eratosthones."""
1+
# -*- coding: utf-8 -*-
2+
3+
"""
4+
Sieve of Eratosthones
5+
6+
The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or equal to a given value.
7+
Illustration: https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
8+
Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
9+
10+
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
11+
Also thanks Dmitry (https://github.com/LizardWizzard) for finding the problem
12+
"""
13+
214

315
import math
416

17+
518
def sieve(n):
6-
"""Sieve of Eratosthones."""
19+
"""
20+
Returns a list with all prime numbers up to n.
21+
22+
>>> sieve(50)
23+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
24+
>>> sieve(25)
25+
[2, 3, 5, 7, 11, 13, 17, 19, 23]
26+
>>> sieve(10)
27+
[2, 3, 5, 7]
28+
>>> sieve(9)
29+
[2, 3, 5, 7]
30+
>>> sieve(2)
31+
[2]
32+
>>> sieve(1)
33+
[]
34+
"""
35+
736
l = [True] * (n + 1)
837
prime = []
938
start = 2
1039
end = int(math.sqrt(n))
40+
1141
while start <= end:
42+
# If start is a prime
1243
if l[start] is True:
1344
prime.append(start)
45+
46+
# Set multiples of start be False
1447
for i in range(start * start, n + 1, start):
1548
if l[i] is True:
1649
l[i] = False
50+
1751
start += 1
1852

1953
for j in range(end + 1, n + 1):

other/finding_primes.py

-21
This file was deleted.

0 commit comments

Comments
 (0)