TheAlgorithms-Python

Форк
0
61 строка · 1.6 Кб
1
"""
2
Project Euler Problem 10: https://projecteuler.net/problem=10
3

4
Summation of primes
5

6
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
7

8
Find the sum of all the primes below two million.
9

10
References:
11
    - https://en.wikipedia.org/wiki/Prime_number
12
    - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
13
"""
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__":
61
    print(f"{solution() = }")
62

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.