Skip to content

Commit 7ec703d

Browse files
authored
solution to euler project problem 10
1 parent ebfd55d commit 7ec703d

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#author-slayking1965
2+
"""
3+
https://projecteuler.net/problem=10
4+
Problem Statement:
5+
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
6+
Find the sum of all the primes below two million using Sieve_of_Eratosthenes:
7+
The sieve of Eratosthenes is one of the most efficient ways to find all primes
8+
smaller than n when n is smaller than 10 million. Only for positive numbers.
9+
Find the sum of all the primes below two million.
10+
"""
11+
12+
13+
def prime_sum(n: int) -> int:
14+
"""Returns the sum of all the primes below n.
15+
def solution(n: int = 2000000) -> int:
16+
"""Returns the sum of all the primes below n using Sieve of Eratosthenes:
17+
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
18+
The sieve of Eratosthenes is one of the most efficient ways to find all primes
19+
smaller than n when n is smaller than 10 million. Only for positive numbers.
20+
>>> prime_sum(2_000_000)
21+
>>> solution(2_000_000)
22+
142913828922
23+
>>> prime_sum(1_000)
24+
>>> solution(1_000)
25+
76127
26+
>>> prime_sum(5_000)
27+
>>> solution(5_000)
28+
1548136
29+
>>> prime_sum(10_000)
30+
>>> solution(10_000)
31+
5736396
32+
>>> prime_sum(7)
33+
>>> solution(7)
34+
10
35+
>>> prime_sum(7.1) # doctest: +ELLIPSIS
36+
>>> solution(7.1) # doctest: +ELLIPSIS
37+
Traceback (most recent call last):
38+
...
39+
TypeError: 'float' object cannot be interpreted as an integer
40+
>>> prime_sum(-7) # doctest: +ELLIPSIS
41+
>>> solution(-7) # doctest: +ELLIPSIS
42+
Traceback (most recent call last):
43+
...
44+
IndexError: list assignment index out of range
45+
>>> prime_sum("seven") # doctest: +ELLIPSIS
46+
>>> solution("seven") # doctest: +ELLIPSIS
47+
Traceback (most recent call last):
48+
...
49+
TypeError: can only concatenate str (not "int") to str
50+
"""
51+
list_ = [0 for i in range(n + 1)]
52+
list_[0] = 1
53+
list_[1] = 1
54+
primality_list = [0 for i in range(n + 1)]
55+
primality_list[0] = 1
56+
primality_list[1] = 1
57+
58+
for i in range(2, int(n ** 0.5) + 1):
59+
if list_[i] == 0:
60+
if primality_list[i] == 0:
61+
for j in range(i * i, n + 1, i):
62+
list_[j] = 1
63+
s = 0
64+
primality_list[j] = 1
65+
sum_of_primes = 0
66+
for i in range(n):
67+
if list_[i] == 0:
68+
s += i
69+
return s
70+
if primality_list[i] == 0:
71+
sum_of_primes += i
72+
return sum_of_primes
73+
74+
75+
if __name__ == "__main__":
76+
# import doctest
77+
# doctest.testmod()
78+
print(prime_sum(int(input().strip())))
79+
print(solution(int(input().strip())))

0 commit comments

Comments
 (0)