mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-01 00:41:09 +00:00
98e9d6bdb6
* Fix style of the first ten solutions for Project Euler - Unify the header docstring, and add reference URLs to wikipedia or similar - Fix docstrings to be properly multilined - Add newlines where appropriate - Add doctests where they were missing - Remove doctests that test for the correct solution - fix obvious spelling or grammar mistakes in comments and exception messages - Fix line endings to be UNIX. This makes two of the files seem to have changed completely - no functional changes in any of the solutions were done (except for the spelling fixes mentioned above) * Fix docstrings and main function as per Style Guide
62 lines
1.6 KiB
Python
62 lines
1.6 KiB
Python
"""
|
|
Project Euler Problem 10: https://projecteuler.net/problem=10
|
|
|
|
Summation of primes
|
|
|
|
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
|
|
|
|
Find the sum of all the primes below two million.
|
|
|
|
References:
|
|
- https://en.wikipedia.org/wiki/Prime_number
|
|
- https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
|
"""
|
|
|
|
|
|
def solution(n: int = 2000000) -> int:
|
|
"""
|
|
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)
|
|
1548136
|
|
>>> solution(10000)
|
|
5736396
|
|
>>> solution(7)
|
|
10
|
|
>>> solution(7.1) # doctest: +ELLIPSIS
|
|
Traceback (most recent call last):
|
|
...
|
|
TypeError: 'float' object cannot be interpreted as an integer
|
|
>>> solution(-7) # doctest: +ELLIPSIS
|
|
Traceback (most recent call last):
|
|
...
|
|
IndexError: list assignment index out of range
|
|
>>> solution("seven") # doctest: +ELLIPSIS
|
|
Traceback (most recent call last):
|
|
...
|
|
TypeError: can only concatenate str (not "int") to str
|
|
"""
|
|
|
|
primality_list = [0 for i in range(n + 1)]
|
|
primality_list[0] = 1
|
|
primality_list[1] = 1
|
|
|
|
for i in range(2, int(n ** 0.5) + 1):
|
|
if primality_list[i] == 0:
|
|
for j in range(i * i, n + 1, i):
|
|
primality_list[j] = 1
|
|
sum_of_primes = 0
|
|
for i in range(n):
|
|
if primality_list[i] == 0:
|
|
sum_of_primes += i
|
|
return sum_of_primes
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print(f"{solution() = }")
|