|
1 |
| -''' |
2 |
| -Using sieve of Eratosthenes, primes(x) returns list of all primes less than x |
| 1 | +""" |
| 2 | +Return list of all primes less than n, |
| 3 | +Using sieve of Eratosthenes. |
3 | 4 |
|
4 | 5 | Modification:
|
5 | 6 | We don't need to check all even numbers, we can make the sieve excluding even
|
6 | 7 | numbers and adding 2 to the primes list by default.
|
7 | 8 |
|
8 |
| -We are going to make an array of: x / 2 - 1 if number is even, else x / 2 |
| 9 | +We are going to make an array of: x / 2 - 1 if number is even, else x / 2 |
9 | 10 | (The -1 with even number it's to exclude the number itself)
|
10 | 11 | Because we just need numbers [from 3..x if x is odd]
|
11 | 12 |
|
|
21 | 22 |
|
22 | 23 | With this, we have reduced the array size to a half,
|
23 | 24 | and complexity it's also a half now.
|
24 |
| -''' |
| 25 | +""" |
25 | 26 |
|
26 |
| -def primes(x): |
27 |
| - assert(x >= 0) |
| 27 | + |
| 28 | +def get_primes(n): |
| 29 | + """Return list of all primes less than n, |
| 30 | + Using sieve of Eratosthenes. |
| 31 | + """ |
| 32 | + if n <= 0: |
| 33 | + raise ValueError("'n' must be a positive integer.") |
28 | 34 | # If x is even, exclude x from list (-1):
|
29 |
| - sieve_size = (x//2 - 1) if x % 2 == 0 else (x//2) |
30 |
| - sieve = [1 for v in range(sieve_size)] # Sieve |
31 |
| - primes = [] # List of Primes |
32 |
| - if x >= 2: |
33 |
| - primes.append(2) # Add 2 by default |
| 35 | + sieve_size = (n // 2 - 1) if n % 2 == 0 else (n // 2) |
| 36 | + sieve = [True for _ in range(sieve_size)] # Sieve |
| 37 | + primes = [] # List of Primes |
| 38 | + if n >= 2: |
| 39 | + primes.append(2) # 2 is prime by default |
34 | 40 | for i in range(sieve_size):
|
35 |
| - if sieve[i] == 1: |
| 41 | + if sieve[i]: |
36 | 42 | value_at_i = i*2 + 3
|
37 | 43 | primes.append(value_at_i)
|
38 | 44 | for j in range(i, sieve_size, value_at_i):
|
39 |
| - sieve[j] = 0 |
| 45 | + sieve[j] = False |
40 | 46 | return primes
|
0 commit comments