Skip to content

Commit a36c6ed

Browse files
itsvinayakstokhos
authored andcommitted
project_euler/problem_10 (TheAlgorithms#1089)
* project_euler/problem_10 * update project_euler/problem_10 * update project_euler/problem_10 * Negative user tests added.
1 parent d8315e7 commit a36c6ed

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Diff for: project_euler/problem_10/sol3.py

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

0 commit comments

Comments
 (0)