Skip to content

Hacktoberfest: Add project euler problem 50 #3016

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 8, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
76 changes: 76 additions & 0 deletions project_euler/problem_50/sol1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""
https://projecteuler.net/problem=50
Consecutive prime sum

Problem 50

The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13

This is the longest sum of consecutive primes that adds to a prime below
one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime,
contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most
consecutive primes?
"""


def sieve(n: int) -> list:
"""
Sieve of Erotosthenes
Function to return all the prime numbers up to a certain number
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
>>> sieve(3)
[2]

>>> sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
"""
is_prime = [True] * n
is_prime[0] = False
is_prime[1] = False
is_prime[2] = True

for i in range(3, int(n ** 0.5 + 1), 2):
index = i * 2
while index < n:
is_prime[index] = False
index = index + i

primes = [2]

for i in range(3, n, 2):
if is_prime[i]:
primes.append(i)

return primes


def solution() -> int:
"""
Returns the solution of the problem
>>> solution()
997651
"""
primes = sieve(1_000_000)
length = 0
largest = 0

for i in range(len(primes)):
for j in range(i + length, len(primes)):
sol = sum(primes[i:j])
if sol >= 1_000_000:
break

if sol in primes:
length = j - i
largest = sol

return largest


if __name__ == "__main__":
print(solution())