Skip to content

Commit 686d837

Browse files
Hyftardhruvmanila
andauthored
Add project euler problem 50 (#3016)
* Add project euler problem 50 * Apply format changes * Descriptive function/parameter name and type hints Co-authored-by: Dhruv Manilawala <[email protected]>
1 parent c0d88d7 commit 686d837

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

project_euler/problem_050/__init__.py

Whitespace-only changes.

project_euler/problem_050/sol1.py

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

0 commit comments

Comments
 (0)