Returns the sum of all the primes below n using Sieve of Eratosthenes: The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million. Only for positive numbers. >>> solution(1000) 76127 >>> solution(5000)
(n: int = 2000000)
| 14 | |
| 15 | |
| 16 | def solution(n: int = 2000000) -> int: |
| 17 | """ |
| 18 | Returns the sum of all the primes below n using Sieve of Eratosthenes: |
| 19 | |
| 20 | The sieve of Eratosthenes is one of the most efficient ways to find all primes |
| 21 | smaller than n when n is smaller than 10 million. Only for positive numbers. |
| 22 | |
| 23 | >>> solution(1000) |
| 24 | 76127 |
| 25 | >>> solution(5000) |
| 26 | 1548136 |
| 27 | >>> solution(10000) |
| 28 | 5736396 |
| 29 | >>> solution(7) |
| 30 | 10 |
| 31 | >>> solution(7.1) # doctest: +ELLIPSIS |
| 32 | Traceback (most recent call last): |
| 33 | ... |
| 34 | TypeError: 'float' object cannot be interpreted as an integer |
| 35 | >>> solution(-7) # doctest: +ELLIPSIS |
| 36 | Traceback (most recent call last): |
| 37 | ... |
| 38 | IndexError: list assignment index out of range |
| 39 | >>> solution("seven") # doctest: +ELLIPSIS |
| 40 | Traceback (most recent call last): |
| 41 | ... |
| 42 | TypeError: can only concatenate str (not "int") to str |
| 43 | """ |
| 44 | |
| 45 | primality_list = [0 for i in range(n + 1)] |
| 46 | primality_list[0] = 1 |
| 47 | primality_list[1] = 1 |
| 48 | |
| 49 | for i in range(2, int(n**0.5) + 1): |
| 50 | if primality_list[i] == 0: |
| 51 | for j in range(i * i, n + 1, i): |
| 52 | primality_list[j] = 1 |
| 53 | sum_of_primes = 0 |
| 54 | for i in range(n): |
| 55 | if primality_list[i] == 0: |
| 56 | sum_of_primes += i |
| 57 | return sum_of_primes |
| 58 | |
| 59 | |
| 60 | if __name__ == "__main__": |