# HG changeset patch # User Dominic Cleal # Date 1228158715 0 # Node ID 49c96972949d647f1734109dbda916fc81ce319e # Parent 836a4ccbcbae34b2dbfff403a26db0cd7430e514 #50 rewrite of solution diff -r 836a4ccbcbae -r 49c96972949d problem50.py --- a/problem50.py Mon Dec 01 13:14:53 2008 +0000 +++ b/problem50.py Mon Dec 01 19:11:55 2008 +0000 @@ -1,35 +1,27 @@ -import math - -def count(i, min): - for a in range(0, len(p) - min): - t = 0 - for b in range(a, len(p)): - t += p[b] - if t == i: - return b - a + 1 - if t > i: - break - return False +import primes -cmax = 0 -imax = 0 -p = [ 2 ] -i = 3 -while i < 1000: - isp = True - max = int(math.floor(math.sqrt(i))) - for t in p[1:]: - if t > max: +def search(pmax): + cur = { } + max = { } + s = primes.testsieve() + for p in s.sieve(): + if p > pmax: break - if i % t == 0: - isp = False - break - if isp: - p.append(i) - c = count(i, cmax) - if not c == False and c > cmax: - cmax = c - imax = i - print "New max %d with %d conseq" % (i, c) - i += 2 + if p not in cur: + cur[p] = (0, 0) + todel = [] + for i in cur: + cur[i] = (cur[i][0] + 1, cur[i][1] + p) + if cur[i][1] > pmax: + todel.append(i) + elif s.isprime(cur[i][1]): + max[i] = cur[i] + for i in todel: + del cur[i] + retmax = None + for i in max: + if retmax is None or max[i][0] > retmax[0]: + retmax = max[i] + return retmax +print "Max conseq has %d terms, totalling %d" % search(1000000)