2 de septiembre de 2012

Project Euler 27


#!/usr/bin/env python
#True if n is prime
def p(n):
    if n==2:
        return True
    if n%2==0:
        return False
    m=int(n**.5)
    for i in xrange(3,m+1,2):
        if n%i==0:
            return False
    return True
#primes<1000 span="span">
plst=[x for x in xrange(2,997) if p(x)]
#primes |a| such that |a|<1000 span="span">
plst2=map(lambda x:-x,plst)+plst
#consecutive primes
def primes(a,b):
    n=0
    while p(abs((n**2)+a*n+b)):
        n+=1
    return n
#find max consecutive primes
cycle=product=tmp=0
for a in plst2:
    for b in plst:
        tmp=primes(a,b)
        if cycle<tmp:
            cycle=tmp
            product=a*b
print product