patternpythonMinor
Project Euler 50 in Python
Viewed 0 times
pythonprojecteuler
Problem
Project Euler, 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?
I came up with this code, but it only works decently for primes below ten thousand.
Any ideas on how to optimize it?
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?
I came up with this code, but it only works decently for primes below ten thousand.
Any ideas on how to optimize it?
from pyprimes import *
def sequence_exists(l,ls,limit = 100):
for x in range(0,len(ls)-l):
if x+l > len(ls): return False
if any (ls[i] > limit/6 for i in range(x,x+l,1)) :
return False
test_sum = sum(ls[x:x+l:1])
if (test_sum <limit) and is_prime(test_sum) :
return True
return False
def main():
n = prime_count(10000)
prime_list = list(nprimes(n))
l = 6
for x in range(6,len(prime_list)):
if sequence_exists(x,prime_list,10000):
l=x
print l
if __name__ == '__main__':
main()Solution
Don't import 'wildcards'
Especially if the module is not part of the Standard Library people will be confused and not understand where the function is coming from. You can cut down typing as follows:
Use longer names
In the above
Especially if the module is not part of the Standard Library people will be confused and not understand where the function is coming from. You can cut down typing as follows:
import pyprimes as prUse longer names
def sequence_exists(l,ls,limit = 100):In the above
l and ls tell nothing to the reader.Code Snippets
import pyprimes as prdef sequence_exists(l,ls,limit = 100):Context
StackExchange Code Review Q#88645, answer score: 3
Revisions (0)
No revisions yet.