题目网址:http://projecteuler.net/problem=27
参考网址:http://www.mathblog.dk/project-euler-27-quadratic-formula-primes-consecutive-values/
代码:
import math,datetime
known={0:False,1:False,2:False}
def isPrime(n):
if n in known:
return known[n]
else:
flag=True
for tempint in xrange(2,min(int(math.sqrt(n)+2),n)):
if not n%tempint:
flag=False
break
known[n]=flag
return flag
start_time=datetime.datetime.now()
maxcount,maxa,maxb=0,-1000,-1000
for a in xrange(-1000+1,1001,1):
for b in xrange(-1000+1,1001,1):
x,tempcount=0,0
while 1:
tempvalue=x*x+a*x+b
if isPrime(abs(tempvalue)):
tempcount,x=tempcount+1,x+1
else:
break
if tempcount>maxcount:
maxcount,maxa,maxb=tempcount,a,b
print maxcount,maxa,maxb,maxa*maxb
end_time=datetime.datetime.now()
print end_time-start_time
坑了,艹 了。。我不要求想出什么很优雅的方法。但是最基本的方法一定要知道做啊。艹 了。
71 -61 971 -59231
0:00:05.787000
看着别人的代码改进的
known={0:False,1:False,2:False}
def isPrime(n):
if n in known:
return known[n]
else:
flag=True
for tempint in xrange(2,min(int(math.sqrt(n)+2),n)):
if not n%tempint:
flag=False
break
known[n]=flag
return flag
start_time=datetime.datetime.now()
maxcount,maxa,maxb=0,-1000,-1000
arrb=[ i for i in xrange(1,1001,1) if isPrime(abs(i))]
for a in xrange(-1000+1,1001,2):
for b in arrb:
x,tempcount=0,0
while 1:
tempvalue=x*x+a*x+b
if tempvalue%2!=0 and isPrime(abs(tempvalue)):
tempcount,x=tempcount+1,x+1
else:
break
if tempcount>maxcount:
maxcount,maxa,maxb=tempcount,a,b
print maxcount,maxa,maxb,maxa*maxb
end_time=datetime.datetime.now()
print end_time-start_time
71 -61 971 -59231
0:00:00.561000