Skip to content

Commit 05069fa

Browse files
committed
Add project euler problem 50
1 parent ff9be86 commit 05069fa

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

project_euler/problem_50/__init__.py

Whitespace-only changes.

project_euler/problem_50/sol1.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
"""
2+
https://projecteuler.net/problem=50
3+
Consecutive prime sum
4+
5+
Problem 50
6+
7+
The prime 41, can be written as the sum of six consecutive primes:
8+
41 = 2 + 3 + 5 + 7 + 11 + 13
9+
10+
This is the longest sum of consecutive primes that adds to a prime below
11+
one-hundred.
12+
13+
The longest sum of consecutive primes below one-thousand that adds to a prime,
14+
contains 21 terms, and is equal to 953.
15+
16+
Which prime, below one-million, can be written as the sum of the most
17+
consecutive primes?
18+
"""
19+
20+
21+
def sieve(n: int) -> list:
22+
"""
23+
Sieve of Erotosthenes
24+
Function to return all the prime numbers up to a certain number
25+
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
26+
>>> sieve(3)
27+
[2]
28+
29+
>>> sieve(50)
30+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
31+
"""
32+
is_prime = [True] * n
33+
is_prime[0] = False
34+
is_prime[1] = False
35+
is_prime[2] = True
36+
37+
for i in range(3, int(n**0.5 + 1), 2):
38+
index = i * 2
39+
while index < n:
40+
is_prime[index] = False
41+
index = index + i
42+
43+
primes = [2]
44+
45+
for i in range(3, n, 2):
46+
if is_prime[i]:
47+
primes.append(i)
48+
49+
return primes
50+
51+
52+
def solution() -> int:
53+
"""
54+
Returns the solution of the problem
55+
>>> solution()
56+
997651
57+
"""
58+
primes = sieve(1_000_000)
59+
length = 0
60+
largest = 0
61+
62+
for i in range(len(primes)):
63+
for j in range(i + length, len(primes)):
64+
sol = sum(primes[i:j])
65+
if sol >= 1_000_000:
66+
break
67+
68+
if sol in primes:
69+
length = j - i
70+
largest = sol
71+
72+
return largest
73+
74+
75+
if __name__ == "__main__":
76+
print(solution())

0 commit comments

Comments
 (0)