Project Euler Problem 50

This is by far one of the least elegant solutions to Problem 50 as posted on the Solutions Forum. It ran for about 400ms including Prime Sieve and Sift-Test, which is not too bad. The recursion is probably not necessary, but it works.

The problem asks:

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

The primeset collection is created for fast look up. Another way to do that is to have a Binary Search function. This is the solution in Python:

 

# find the longest prime chain
def genprime(n):  # adopted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178
    if n==2: return [2]
    elif n<2: return []
    s=range(3,n+1,2)
    mroot = n ** 0.5
    half=(n+1)/2-1
    i=0
    m=3
    while m <= mroot:
        if s[i]:
            j=(m*m-3)/2
            s[j]=0
            while j<half:
                s[j]=0
                j+=m
        i=i+1
        m=2*i+3
    return [2]+[x for x in s if x]
    
import time
ts = time.clock()
primes = genprime(10**6)
primeset = set(primes)
initsum = 0
for i in xrange(len(primes)):
    if initsum > 10**6:
        initsum -= primes[i-1]
        primes = primes[:i-1]
        break
    else:
        initsum+= primes[i]
    
def recursiveCount(cursum, curlen, ub):
    if cursum <= 2:    return 1
    global primeset, primes
    cur, lb, hasPrimeSum, oldub = cursum, 0, 0, ub
    for i in xrange(curlen):
        hasPrimeSum = cur in primeset
        if hasPrimeSum:
            break
        elif ub<len(primes)-1:
            cur += (-primes[lb] + primes[ub+1])
            lb, ub = lb+1, ub+1
    if hasPrimeSum:
        return cur
    else:
        return recursiveCount(cursum-primes[oldub], curlen+1, oldub-1)
        
print recursiveCount(initsum, 1, len(primes)-1), " took %s seconds" % (time.clock() - ts) 

 

 

Posted on 2/19/2008 5:55:00 PM by Haoest

Permalink | Comments (1) | Post RSSRSS comment feed |

Categories: Project Euler | Python

Tags:

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

August 10. 2008 04:52

andrew

you're a douchebag

andrew us

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

November 19. 2008 10:15