Skip to content

Commit 6a64fbe

Browse files
authored
hacktoberfest
1 parent 6e5a76a commit 6a64fbe

File tree

1 file changed

+79
-1
lines changed

1 file changed

+79
-1
lines changed

project_euler/problem_050/sol1.py

+79-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,79 @@
1-
1+
"""
2+
Project Euler Problem [50]: https://projecteuler.net/problem=50
3+
4+
5+
The prime 41, can be written as the sum of six consecutive primes:
6+
41 = 2 + 3 + 5 + 7 + 11 + 13
7+
8+
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
9+
10+
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
11+
12+
Which prime, below one-million, can be written as the sum of the most consecutive primes?
13+
"""
14+
15+
16+
def is_prime(number: int) -> [bool]:
17+
"""
18+
Test to see if the number is prime
19+
"""
20+
i = 2 # begin from the smallest prime
21+
22+
# if the number is a composite then it will atleat have a
23+
# factor less than equal to its square root
24+
25+
while i * i <= number:
26+
# if number is divisible by i then i is a factor of number
27+
if number % i == 0:
28+
return False
29+
i += 1
30+
return True
31+
32+
def sieve_of_eratosthenes(limit: int) -> [list]:
33+
"""
34+
Returns a list of boolean values that indicate
35+
whether number at a given index is prime
36+
"""
37+
is_prime_number = [True] * (limit + 1)
38+
i = 2 # begin from the smallest prime
39+
while i * i <= limit:
40+
if is_prime_number[i]:
41+
for j in range(2*i, limit + 1, i):
42+
is_prime_number[j] = False
43+
i += 1
44+
return is_prime_number
45+
46+
def solution(limit: int = 1_000_000):
47+
"""
48+
Get the prime number less than limit which is
49+
longest sum of consecutive primes.
50+
51+
>>> solution(100)
52+
41
53+
>> solution(1000)
54+
953
55+
"""
56+
prime_number = 0 #result
57+
max_length = 0 #length
58+
is_prime_number = sieve_of_eratosthenes(limit)
59+
primes = []
60+
for i in range(2, limit):
61+
if is_prime_number[i]:
62+
primes.append(i)
63+
for i in range(len(primes)):
64+
total = 0
65+
for j in range(i, len(primes)):
66+
total += primes[j]
67+
if total >= limit:
68+
break
69+
if is_prime(total):
70+
if max_length < j - i + 1:
71+
prime_number = total
72+
max_length = j - i + 1
73+
74+
return prime_number
75+
76+
if __name__ == "__main__":
77+
print(f"{solution() = }")
78+
79+

0 commit comments

Comments
 (0)